【问题标题】:What is the difference between a prototype function inside or outside the "class" definition [duplicate]“类”定义内部或外部的原型函数有什么区别[重复]
【发布时间】:2012-12-02 18:26:34
【问题描述】:

可能重复:
Use of ‘prototype’ vs. ‘this’ in Javascript?
Defining prototype methods inside the constructor

这两个定义有区别吗?

function Task(description, value) {

    this.id = 0;
    this.subId = 0;
    this.parent = null;
    this.children = new Array();

    this.description = description;
    this.value = value;

    Task.prototype.getNextId = function () {
       return this.subId++;
    },

    Task.prototype.addTask = function (task) {
        task.id = this.getNextId();
        this.children[task.id] = task;
        task.parent = this;
    },

    Task.prototype.remove = function () {
        this.parent.children.remove(this.id);
    }

}

所有原型方法都在任务定义中,或者?

function Task(description, value) {

    this.id = 0;
    this.subId = 0;
    this.parent = null;
    this.children = new Array();

    this.description = description;
    this.value = value;

}

Task.prototype.getNextId = function () {
   return this.subId++;
},

Task.prototype.addTask = function (task) {
    task.id = this.getNextId();
    this.children[task.id] = task;
    task.parent = this;
},

Task.prototype.remove = function () {
    this.parent.children.remove(this.id);
}

我不确定是否有区别。从 OOP 的角度来看,内部定义看起来更好。

谢谢!

【问题讨论】:

  • Defining prototype methods inside the constructor 应该回答您的问题(或至少有助于理解差异)。
  • 每次调用构造函数时都会执行“内部”,因此您不想将原型方法定义放在那里。有胆量是 JavaScript“类”:P 的商标
  • @DCoder,我不这么认为。他问的是把原型方法放在构造函数内部还是外部;我不明白“这个”是如何涉及的。
  • @DCoder:在这种情况下,函数被分配给构造函数内部的Task.prototype,而不是this。这是两种不同的场景。不是重复的。
  • 非常感谢。我认为这个stackoverflow.com/questions/7115594/… 是我搜索的内容。

标签: javascript methods prototype


【解决方案1】:

构造函数的prototype 是一个在从构造函数创建的实例之间共享的对象。

如果您在构造函数中更新prototype 对象的属性,则共享该原型对象的所有实例都将引用最新的更新。

在您的代码中,您不会注意到差异,但它仍然是错误的。无需继续用新的相同版本覆盖原型函数。

如果您的代码发生更改,以便添加到 prototype 的函数引用构造函数中的局部变量,那么所有实例最终将使用引用最新调用中的变量的原型函数。这几乎不是您想要的。

如果您的代码发生更改,从而覆盖了构造函数的整个原型对象,那么创建的每个实例都将引用不同的原型对象,并且您将无法通过添加新方法来更新所有实例的原型Task.prototype,因为它只会更新最新实例的原型对象。

【讨论】:

    【解决方案2】:

    第一个在每次调用构造函数时分配原型函数。因此,如果您稍后将它们重新分配到其他地方,那么只要您构造另一个该类型的基础对象,它们就会再次被覆盖。这几乎总是不受欢迎的。

    有关更详细的讨论,请参阅此问题:Defining prototype methods inside the constructor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2019-02-28
      • 2011-08-20
      • 2016-11-13
      相关资源
      最近更新 更多