是否可以使用"这个"在构造函数中创建属性?

时间:2017-11-01 17:25:53

标签: javascript

在下面的constructor function中,我没有为每个属性声明一个新变量。相反,我为每个属性使用了this关键字。例如,我没有声明var species;,而是在函数内部使用this.species。这适用于chrome,它使我不必声明一堆变量。但有一个明显的原因是我不应该以这种方式创建constructor function属性吗?它是否被认为是草率的,还是在业界普遍不赞成?



'use strict';
	
var zombie;
	
const Creature = function() {
  this.species = null;
  this.action = null;
  this.story = function() {
    console.log("The " +this.species +" is about to " +this.action +".");
  }
}
	
zombie = new Creature();
	
zombie.species = "zombie";
zombie.action = "strike";
	
zombie.story();




3 个答案:

答案 0 :(得分:1)

不仅如此,这是正确的方法。在构造函数中声明变量只会使它们成为构造函数中的变量,它不会使它们成为实例的属性。您正在做什么 使它们成为属性,并且是正确的(并且得到IDE代码完成的良好支持;例如,稍后如果您键入zombie.,则IDE知道zombie }可能有speciesactionstory,并且可以自动建议它们。

有点切向,但除非你有充分的理由为每个实例创建单独的story函数,否则将它放在将被指定为新对象原型的对象上:

const Creature = function() {
  this.species = null;
  this.action = null;
};
Creature.prototype.story = function() {
  console.log("The " +this.species +" is about to " +this.action +".");
};

如果您正在使用构造函数,因为您已经在使用ES2015 +功能(const),您可以考虑使用class

class Creature {
  constructor() {
    this.species = null;
    this.action = null;
  }
  story() {
    console.log("The " +this.species +" is about to " +this.action +".");
  }
}

...因为它更简洁,更具说服力。此外,它会阻止您在没有Creature的情况下调用new

另外,而不是

zombie = new Creature();
zombie.species = "zombie";
zombie.action = "strike";

...您可以在构造函数中初始化这些属性:

class Creature {
  constructor(species, action) {
    this.species = species;
    this.action = action;
  }
  story() {
    console.log("The " +this.species +" is about to " +this.action +".");
  }
}

然后:

zombie = new Creature("zombie", "strike");

(社区维基,因为这主要是对问题的评论所说的,只是扩展了一点。)

答案 1 :(得分:1)

你应该使用构造函数来传递这些值,而不是在之后执行:

'use strict';

var zombie;

const Creature = function(species, action) {
  this.species = species;
  this.action = action;
  this.story = function() {
    console.log("The " +this.species +" is about to " +this.action +".");
  }
}

zombie = new Creature("zombie", "strike");

zombie.story();

原因是当其他人使用您的课程时,如果他们滥用您的课程,IDE会给出明确的指示或显示警告。如果团队合作或生成供他人使用的代码,则要求您的类使用得到明确定义和清晰。这个例子显然是人为的,但是story()函数的使用似乎期望设置这两个属性,因此在构造时应该是必需的。

答案 2 :(得分:0)

你必须小心引用'this'。虽然您知道构造函数中的“this”是什么,但您知道它在对象的方法中是什么吗?如何在对象外部调用该方法?在ecmascript5中,我总是在对象的闭包中创建一个成员'self',并在构造函数中将它赋给self。这样我总是知道自己在其他方法中所指的是什么。 e.g。

  const Creature = function(species, action) {
    var self = this;
    self.species = species;
    self.action = action;

    self.story = function() {
      console.log("The " +self.species +" is about to " +self.action +".");
    }
  }

请参阅此答案,了解其在javascript How does the "this" keyword work?

中的工作原理

妙语是'this'绑定到调用者的范围。因此,它并不总是意味着包含对象的实例,就像在Java中一样。

相关问题