简体   繁体   English

在构造函数中使用“ this”与“ .prototype”

[英]Using “this” versus “.prototype” inside the constructor function

Could someone please explain the differences of the two code below using a constructor function. 有人可以使用构造函数来说明下面两个代码的区别。 They both give the same results. 它们都给出相同的结果。 Does one have an advantage over the other? 一个人比另一个人有优势吗?

function Person(){
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
}

var person1 = new Person();
var person2 = new Person();

person1.name = "Greg";
alert(person1.name);   //"Greg"  from instance
alert(person2.name);   //"Nicholas" from prototype

VERSUS

function Person(){
  this.name = "Nicholas";
  this.age = 29;
}

var person1 = new Person();
var person2 = new Person();

person1.name = "Greg";
alert(person1.name);   // "Greg"  from instance
alert(person2.name);   // "Nicholas" from Person Object?     

They're doing something different. 他们正在做一些不同的事情。

The first one is assigning the same details to the prototype on each invocation of the constructor. 第一个是在每次构造函数调用时为原型分配相同的详细信息。 These details will be shared by every object created via this constructor. 这些细节将由通过此构造函数创建的每个对象共享。 This is definitely not what you should be doing. 这绝对不是您应该做的。 Generally, only methods should be added to the prototype, and definitely not within the constructor's body. 通常,仅应将方法添加到原型中,并且绝对不要在构造函数的主体内添加方法。 It should happen outside of the constructor (it's just running pointless code needlessly and will be confusing to other developers). 它应该在构造函数之外发生(它只是在不必要地运行无意义的代码,并且会使其他开发人员感到困惑)。

The second, those properties are local to the constructed object returned, which is this in that context. 第二,这些属性对于返回的构造对象是本地的,在这种情况下就是this This is the correct way of having instance properties. 这是拥有实例属性的正确方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM