JavaScript原型问题
目前,我正在阅读“面向对象的JavaScript”。 此外,我在执行书中的示例时遇到了一个小问题 下面是代码示例:JavaScript原型问题,javascript,Javascript,目前,我正在阅读“面向对象的JavaScript”。 此外,我在执行书中的示例时遇到了一个小问题 下面是代码示例: var Dog = function() { this.tail = true; }; var benji = new Dog(); var rusty = new Dog(); Dog.prototype.say = function() { return "Woof!"; }; benji.say(); rusty.say(); Dog.prototype =
var Dog = function() {
this.tail = true;
};
var benji = new Dog();
var rusty = new Dog();
Dog.prototype.say = function() { return "Woof!"; };
benji.say();
rusty.say();
Dog.prototype = {
paws: 4,
hair: true
};
Dog.prototype.constructor = Dog;
var lucy = new Dog();
lucy.say();
基本上,其想法是进行以下工作:
Dog.prototype = {
paws: 4,
hair: true
};
您创建了一个全新的原型对象(您正在为原型对象分配一个新对象)。新的Dog
对象将无法使用方法say()
,旧对象也无法使用属性paws
和hair
你想要:
Dog.prototype.paws = 4;
Dog.prototype.hair = true;
您可以尝试:
console.log(benji.__proto__ === rusty.__proto__); // prints true
console.log(lucy.__proto__ === rusty.__proto__); // prints false
和
console.dir(x.\u proto\u)
应该向您显示原型对象的属性(至少在Chrome中是这样)。什么“hiccup”?什么是奇怪的?引用自书中:原来我们的旧对象无法访问新原型的属性;他们仍然保留指向旧原型对象的秘密链接。最令人困惑的部分是当您查找构造函数的原型时:typeof lucy.constructor.prototype.paws“undefined”typeof benji.constructor.prototype.paws“number”以下内容将修复上述所有意外行为:Dog.prototype={paws:4,hair:true};Dog.prototype.constructor=Dog;*注意,当您覆盖原型时,重置构造函数属性是一个很好的做法。是的,它将修复lucy.constructor.prototype.paws
,但它不会给出lucy
方法。以下工作:var Dog=function(){this.tail=true;this.foo={};};var benji=new Dog();var rusty=new Dog();Dog.prototype.say={cat:114,Dog:foo};Dog.prototype={paws:4,hair:true};Dog.prototype.constructor=Dog;var lucy=new Dog();lucy.foo=benji.say;console.log(benji.say.cat);console.log(benji.say.Dog);console.log(benji.constructor.prototype.hair);console.log(benji.constructor.prototype.paws);console.log(lucy.foo.cat);console.log(lucy.foo.dog);console.log(lucy.hair);console.log(lucy.paws);