【发布时间】: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