哪个更好?
这个实现
var Animal = function(){
this.properties = {};
for(var key in Animal.prototype.properties) this.properties[key] = Animal.prototype.properties[key];
};
Animal.prototype.properties = {
name: 'animal'
};
或者这个
var AnimalV2 = function(){
this.properties = Object.create(AnimalV2.prototype.properties);
};
AnimalV2.prototype.properties = {
name: 'animalv2'
};
当我更改原型(prototype)属性时,它只会影响第二个实现。
var dog = new Animal()
var cat = new AnimalV2();
Animal.prototype.properties.name = 'hello world';
AnimalV2.prototype.properties.name = 'hello world';
console.log(dog.properties.name); // 'animal'
console.log(cat.properties.name); // 'hello world'
正如我们所见,dog.properties 不再与 Animal.prototype.properties 相关联。是性能更好还是代码质量更好?
最佳答案
嗯,在第一种情况
var Animal = function(){
this.properties = {};
for(var key in Animal.prototype.properties)
this.properties[key] = Animal.prototype.properties[key];
};
Animal.prototype.properties = {
name: 'animal'
};
您正在迭代所有属性并逐一分配它们,因此随着第二个属性中 Animal.prototype.properties 中包含更多属性,其成本会更高:
var AnimalV2 = function(){
this.properties = Object.create(AnimalV2.prototype.properties);
};
AnimalV2.prototype.properties = {
name: 'animalv2'
};
您正在创建一个新对象并将其 [[Prototype]] 属性分配给 AnimalV2.prototype.properties,因此无论 AnimalV2.prototype.properties 有多少个属性,都只需要一次分配。
TL;博士 所以从性能和优雅的 Angular 来看,第二种是更好的方法。
如果是干净的代码,我不喜欢其中任何一个,我更喜欢始终在构造函数上保留属性并保留方法的原型(prototype),这对于非 JavaScript 程序员来说很简单。 (而且速度也会更快)
AnimalV3 = function() {
this.properties = {
prop1: 'a',
prop2: 'b'
};
}
关于javascript - 属于实例的对象是否应该与原型(prototype)保持链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12509885/