Я сделал быстрый поиск, но, похоже, не нашел ответа на этот вопрос, только вещи, относящиеся к копированию прототипов функций при наследовании. Почему бы не добавить свойства в прототип функции-конструктора obj вместо использования ключевого слова this. Я уверен, что есть причина не делать этого, но я пытаюсь лучше понять нюансы javascript. например, в обычном наследовании прототипа вы бы использовали "это".
function Dog(name,age,breed){
this.name=name;
this.age=age;
this.breed=breed;
}
Dog.prototype.bark=function(){console.log("bark bark bark");}
let spike=new Dog("Spike",6,"lab");
let rover=new Dog("Rover",8,"poodle");
//^with the constructor function, no instance has the bark function but
//but refers to the same function on the constructor prototype obj, so the
//same function isn't being duplicated. However new keyword changes the
//context of this to refer to the obj so these properties are duplicated
//on every instance.
//I'm curious as to the reason why new doesn't change this to refer to the
//prototype obj for example and then have the instance refers its
//constructor's prototype like with the bark function?
//for example why isn't this a common pattern and what are the reasons I
//should use it.
function Dog(name,age,breed){
Dog.prototype.name=name;
Dog.prototype.age=age;
Dog.prototype.breed=breed;
}
let spike=new Dog("Spike",6,"lab");
let rover=new Dog("rover",8,"poodle");
//I feel like the above code would be more DRY, I'm sure there is a reason
// this isn't common and I'm curious as to why
spike.name
, когда вы делаете это по-своему, и вы поймете, почему люди не делают этого по-вашему. - person user2357112 supports Monica   schedule 31.12.2016