funciton Dog(){
this.tail = true;
}
var benji = new Dog();
var rusty = new Dog();
Dog.prototype.say = function(){
return ' Woof ! ';
}
>>>benji,say(); constructor->Dog()
""Woof !"
var instead = {paws: 4,hair:true}; constructor->Object()
>>>Dog.prototype =instead; constructor ->Object()
>>>benji.paws constructor->Dog()
"undefined"
>>>benji.say() constructor->Dog()
"Woof!"
var lucy = new Dog(); constructor->Object()
>>>lucy.say()
"TypeError:lucy.say is not a function"
>>>lucy.paws
4
解决办法:
Dog.prototype = {paws: 4, hair: true};
Dog.prototype.constructor = Dog;
本文通过一个具体的示例探讨了JavaScript中构造函数、原型对象及原型链的工作原理。展示了如何为构造函数添加方法和属性,并讨论了修改原型对象对实例的影响。
1997

被折叠的 条评论
为什么被折叠?



