Sunday, June 16, 2013

inheritanceInAction, Prototype-based_programming


http://en.wikipedia.org/wiki/Prototype-based_programming

inheritanceInAction();
function inheritanceInAction() {
function A() {
this.a = 1;
}
function B() {
this.b = 2;
}
B.prototype = new A();
B.prototype.constructor = B;

function C() {
this.c = 3;
}
C.prototype = new B();
C.prototype.constructor = C;

var c = new C();

// instanceof expects a constructor function

console.log(c instanceof A); // true
console.log(c instanceof B); // true
console.log(c instanceof C); // true

// isPrototypeOf, can be used on any object
console.log(A.prototype.isPrototypeOf(c)); // true
console.log(B.prototype.isPrototypeOf(c)); // true
console.log(C.prototype.isPrototypeOf(c)); // true

}


The "constructor" property is a reference to the function that created the object's prototype, not the object itself.
The usual way to deal with this is to augment the object's prototype constructor property after assigning to the prototype.


o instanceof p.constructor
instead of
p.isPrototypeOf(o)

No comments:

Post a Comment