Search

6/23/2010

When you overwrite the prototype, it is a good idea to reset the constructor property.

When you overwrite the prototype, it is a good idea to reset the constructor property.
* constructor.prototype.constructor will point to the constructor itself.


function Dog() {
this.tail = true;
}
Dog.prototype.say = function () {
return 'Woof!'
}

var benji = new Dog();
console.log(benji.constructor.prototype.constructor); // Dog {}

// completely replace the prototype object,
// new objects create from now on will use the updated prototype.
Dog.prototype = {paws:4, hair:true};

var lucy = new Dog();

console.log(benji.__proto__); // Object {}
console.log(lucy.__proto__); // Object {paws=4, hair=true}

console.log(typeof benji.paws); // undefined
console.log(typeof benji.say); //function
console.log(typeof benji.paws); // undefined

// the constructor property of the new objects no longer reports correctly.
console.log(lucy.constructor); // Object()
console.log(benji.constructor); // Dog()

// to fix it.
Dog.prototype.constructor = Dog;


var F = function() {}, i;
F.prototype=superc.prototype;
subc.prototype=new F(); // rewrite the prototype.
subc.prototype.constructor=subc; // <--
subc.superclass=superc.prototype;


The prototype chain is live with the exception of when you completely replace the prototype object

function Dog(){this.tail = true;}
var benji = new Dog();
var rusty = new Dog();
Dog.prototype.say = function(){return 'Woof!';}

// completely overwrite the prototype
Dog.prototype = {paws: 4, hair: true};

// It turns out that our old objects do not get access to the new prototype's properties; they still keep the secret link pointing to the old prototype object:
console.log(typeof benji.paws); // undefined
console.log(benji.say()); // Woof!
console.log(typeof benji.__proto__.say); // function
console.log(typeof benji.__proto__.paws); // undefined

var lucy = new Dog();
lucy.say(); // TypeError: lucy.say is not a function
console.log(lucy.paws); // 4
console.log(typeof lucy.__proto__.say); // undefined
console.log(typeof lucy.__proto__.paws); // number


// Now the constructor property of the new objects no longer reports correctly. It should point to Dog(), but instead it points to Object()
lucy.constructor // Object()
benji.constructor // Dog()

// The most confusing part is when you look up the prototype of the constructor
console.log(typeof lucy.constructor.prototype.paws) // undefined
console.log(typeof benji.constructor.prototype.paws) // number

沒有留言: