87,997
社区成员




function Dog(name){
this.name=name;
}
let dogA=new Dog('Paul');
Dog.prototype.eat=true;
dogA.eat; //true,获得构造函数的eat属性
Dog.prototype=null; //将构造函数的原型改为null
dogA.eat; //true 。。。怎么实例对象还有eat?
let dogA.__proto__=Dog.prototype={eat: true};
Dog.prototype=null;
dogA.__proto__; //{eat: true}, 没变
let dogB=new Dog();
dogB.eat; //undefined
比较基础的知识,惭愧。
[/quote]
原型不是这样用的,是已经建立的类想扩展,你可以写个添加原型的属性。这样就和真正面向对象的扩展类相近的意思了。
添加属性和方法
有的时候我们想要在所有已经存在的对象添加新的属性或方法。
另外,有时候我们想要在对象的构造函数中添加属性或方法。
使用 prototype 属性就可以给对象的构造函数添加新的属性:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
当然我们也可以使用 prototype 属性就可以给对象的构造函数添加新的方法:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
let dogA.__proto__=Dog.prototype={eat: true};
Dog.prototype=null;
dogA.__proto__; //{eat: true}, 没变
let dogB=new Dog();
dogB.eat; //undefined
比较基础的知识,惭愧。