function Animate() {
this.age = 12
}
Animate.prototype = {
say() {
console.log(this.age)
}
}
new Animate().say()
function Dog() {}
Dog.prototype = Animate.prototype// 请问这个也可以用Object.create(Animate.prototype),那么用和不用有什么区别吗,求解
let dog = new Dog()
dog.say()
1.首先Animate.prototype 代表Animate的原型 而Object.create(Animate.prototype) 创建Animate的原型的子类对象 this.age是在Animate本身对象中,而非在原型中,所以 Dog.prototype = Animate.prototype要改成Dog.prototype = new Animate();
https://blog.csdn.net/blueblueskyhua/article/details/73135938
Dog.prototype = Animate.prototype 和Dog.prototype = Object.create(Animate.prototype)是有很大区别的。
当使用= 号时表示赋值,那么 Dog.prototype和Animate.prototype 就指向了同一个对象,你向Dog.prototype添加Dog对象的共享方法时,Animate.prototype 也同时拥有了该方法 。比如Dog.prototype.eat =function(){console.log('吃骨头')}, Animate.prototype也就拥有了eat方法。new Animate().eat()同样调用成功。你会发现所有的animal 都有了eat方法,并且是吃骨头,但显然是不对的,并不是每一个animail 对象都吃骨头。
如果使用Dog.prototype = Object.create(Animate.prototype) 就不一样了,Object.create(Animate.prototype)返回一个全新的对象,这个对象链接到了Animate.prototype, 给Dog.prototype 添加方法,是给这个全新的对象添加方法,而不是对Animail.prototype. 所以给Dog.prototype 添加的方法,只会给dog对象共享,对animail 对象没有任可影响
没区别。是不同的构造对象的方式罢了。
你得注意 dog.__proto__.construtor
,你覆盖了原型,却没有更改相应的 constructor。这个是很大的问题。