繁体   English   中英

Javascript原型属性被遮盖

[英]Javascript prototype property shadowed

我对Javascript原型制作机制有些困惑。 我有以下代码:

function Person () {
  this.name = "no name";
  this.setName = function (n) {
    this.name = n;
  }
}

function Student () {
  this.id = "123";
}
Student.prototype = new Person();

s = new Student();
s.setName("Klaus");

执行代码后,对象s有两个名称。 对象本身的名称为“ Klaus”,原型中的名称为“ no name”。 我知道该属性已被遮盖并且可以正常工作,但这不自然吗? 是否有更好的方法仅使用原型的属性?

您可以直接使用prototype属性,但是这会花费不成比例的精力,因此可能不被视为最佳实践。 相反,您可以在this上下文的右侧调用Person构造函数。

首先,强烈建议在分配给函数的prototype属性时使用Object.create而不是new Operator。 使用new Operator时,将调用Person构造函数,但是在this情况下会出错。 为了防止这种情况,您可以像这样链接它们:

Student.prototype = Object.create(Person.prototype);

相反,如果你要拨打的原型链接(的构造Person内学生),你可以call它与正确的构造this背景下:

function Student () {
  Person.call(this);
  this.id = "123";
}

另外,除非您要为每个实例创建一个函数,否则我将setName函数移至Person[[Prototype]]

function Person () {
  this.name = "no name";
}

Person.prototype.setName = function (n) {
  this.name = n;
}

function Student () {
  Person.call(this); // Call the Person constructor
  this.id = "123";
}
Student.prototype = Object.create(Person.prototype);

s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'

另外,如@Teemu所述,您还可以将name属性放置在Person.prototype上,以将其用作默认值:

function Person () {
}

Person.prototype.setName = function (n) {
  this.name = n;
}

Person.prototype.name = "no name"; // Define the name directly

function Student () {
  Person.call(this); // you only need this, if there are other things happening in the Person constructor that you need as well
  this.id = "123";
}
Student.prototype = Object.create(Person.prototype);

s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'

暂无
暂无

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

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