JavaScript:在Constructor.prototype上定义属性的位置?

时间:2016-02-14 08:54:51

标签: javascript constructor

我习惯于以这种方式使用构造函数:

function Computer(ram) {
  this.ram = ram;
}

// Defining a property of the prototype-
// object OUTSIDE of the constructur-
// function.
Computer.prototype.getRam = function() {
  return this.ram + ' MB';
}

我在构造函数中定义和初始化值。方法附加在原型对象外部构造函数。

昨天我见过这些技巧:

function Car(maxSpeed) {
  this.maxSpeed = maxSpeed;
  // Defining a property of the prototype-
  // object WITHIN the constructur-
  // function.
  Car.prototype.getMaxSpeed = function() {
    return this.maxSpeed + ' km/h';
  }
}

该方法在 中定义构造函数=>如果不创建至少一个对象,则该方法不存在。

我总是认为第一种方法有点奇怪,有人可以在构造函数-object上调用方法。然后,使用this-keyword的所有属性都返回undefined。 使用第二种技术会引发错误。

这两种技术的优点和缺点是什么?

我应该选择/避免哪一个以及出于什么原因?

0 个答案:

没有答案
相关问题