2016-12-31 78 views
0

我做了一个快速搜索,但似乎无法找到这个问题的答案,只是指继承时复制函数原型。 为什么不将属性添加到构造函数原型obj中,而不是使用this关键字。我确信有一个理由不会,但我想更好地理解JavaScript的细微差别。例如在正常的原型继承中,你会“this”。原型继承和原型对象,为什么不用这个程度?

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 
+0

看看'spike.name'是什么时候你做你的方式,你会明白为什么人们不这样做你的方式。 – user2357112

回答

3

当你在原型有properties,你将覆盖与新值每次实例化,即在你的榜样类的时间属性,从两个语句如下:

let spike=new Dog("Spike",6,"lab"); 

let rover=new Dog("rover",8,"poodle"); 

这里,根据根据您的预期,spike.name应该是Spikerover.name应该是rover,但是如果您执行此代码并检查,它们都是rover

当您创建新实例rover时,spike的属性将被rover的属性覆盖。 每次创建一个新的实例时,属性都被覆盖,其原因是 methodsproperties附加到原型只创建一次,每次创建新实例时都会继承到它们的子类

我们从中创建构造函数和新实例的原因是因为我们对每个实例都有不同的属性,如Spikerover。在方法的情况下,方法对于构造函数是通用的,对于每次创建新实例时不需要创建的所有实例,这些方法都可以重复使用,因此,我们将它们附加到prototype而不是在构造函数中使用this关键字进行定义。