Inheritance

prototype

good tutorial
http://beej.us/blog/data/javascript-prototypes-inheritance/
http://www.javascriptkit.com/javatutors/oopjs2.shtml

function Kitten() {
  this.fuzzy = true;
}
 
Kitten.prototype.sing = function() {
  return this.fuzzy;
}
 
k = new Kitten()
 
> typeof k
'object'
> typeof Kitten.prototype
'object'
> typeof k.prototype
'undefined'
> typeof k._proto_
'undefined'
> typeof k.__proto__
'object'
> k.__proto__ == Kitten.prototype
true
> k.__proto__ === Kitten.prototype
true
 
> typeof Kitten
'function'
> Kitten.prototype.constructor
[Function: Kitten]
 
> k instanceof Kitten
true
> k instanceof Function
false
> k instanceof Object
true
> Kitten instanceof Function
true
 
> k.constructor
[Function: Kitten]

kitten.prototype is an object, ie. instance of Object()
k. prototype is equal to the prototype property of its constructor function Kitten.

prototype chain

if an object doesn't have the property you're looking for, the property is looked for in that object's prototype object. the object's prototype is an object.

this keyword

http://www.quirksmode.org/js/this.html

objectgetprototypeof

http://ejohn.org/blog/objectgetprototypeof/

OO javascript

  1. approach 1 http://mckoss.com/jscript/object.htm
  2. approach 2 : https://code.google.com/p/closure-library/source/browse/closure/goog/base.js#1519
 function DeriveFrom(child_class, parent_class) {
   // create a Bridge class to avoid creating complex parent_class instance as child_class.prototype, because in inheritance, we normally do it like the following, refer: http://beej.us/blog/data/javascript-prototypes-inheritance/
   // child_class.prototype = new parent_class() 
   // child_class.prototype.constructor = child_class. 
 
   var Bridge = function() {};
   // change Bridge constructor's prototype from Object instance to parent_class constructor's prototype.
   Bridge.prototype = parent_class.prototype;
 
   // change child_class constructor's prototype from Object instance to Bridge object.
   child_class.prototype = new Bridge();
   child_class.prototype.constructor = child_class;
 
   // add a constructor property: super
   child_class.super = parent_class.prototype;
 
   // cautions step only. 
   parent_class.prototype.constructor = parent_class; 
 }
 
  function GoodKitten() {
      Kitten.super.constructor.call(tihs)
      ....
  }  
 
  DeriveFrom(GoodKitten, Kitten)
 
  GoodKitten.prototype.sing = function() {
    return Kitten.super.sing.call(tihs) + " a song."  
  }
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License