什么更好?
这个实现
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'
};
当我更改原型属性时,它只会影响第二个实现。
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 相关联。是性能更好还是代码质量更好?