Search

6/01/2010

javascript prototype

__proto__ is not the same as prototype. __proto__ is a property of the instances(object), whereas prototype is a property of the constructor functions(function).


var o = {};
console.log(o.__proto__); // Object { }
console.log(o.prototype); // undefined
console.log(o.__proto__ == Object.prototype); // true, means pointing to the same object
console.log(o.constructor.prototype == o.__proto); // true



function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}

Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
};

var newtoy = new Gadget('webcam', 'black');

console.log(newtoy) // Object {name="webcam", more...}
console.log(newtoy.constructor); // Gadget(name, color)
console.log(newtoy.constructor.prototype); // Object {price=100, more...}
console.log(newtoy.constructor.prototype.constructor); // Gadget (name, color)


Every object also gets the isPrototypeOf() method. This method tells you whether that specific object is used as a prototype of another object.

var monkey = {
feeds: 'benana',
breathes: 'air'
};

function Human() {};
Human.prototype = monkey;

var developer = new Human();
developer.feeds = 'pizza';
developer.hacks = 'JavaScript';

console.log(developer.__proto__); // Object { feeds="benana", more...}
console.log(typeof developer.__proto__); // object
console.log(typeof developer.prototype); // undefined
console.log(monkey.isPrototypeOf(developer)); // true, relationship between obejects
console.log(monkey.isPrototypeOf(Human)); // false


Prototype Chaining
As you already know, every function has a prototype property, which contains an object. When this function is invoked using the new operator, an object is created and this object has a secret link to the prototype object. The secret link (called __proto__ in some environments) allows methods and properties of the prototype object to be used as if they belong to the newly-created object.

function Shape(){
this.name = 'shape';
this.toString = function() {return this.name;};
}

function TwoDShape(){
this.name = '2D shape';
}

function Triangle(side, height) {
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){return this.side * this.height / 2;};
}
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();

沒有留言: