Javascript “内部”或“外部”的原型函数之间有什么区别;“类”;定义
可能重复:Javascript “内部”或“外部”的原型函数之间有什么区别;“类”;定义,javascript,methods,prototype,Javascript,Methods,Prototype,可能重复: 这两个定义有什么区别吗 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 = functi
这两个定义有什么区别吗
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视图来看,内部定义看起来更好
谢谢 第一个函数在每次调用构造函数时分配原型函数。因此,如果以后在其他地方重新分配这些对象,则每当构造该类型的另一个基本对象时,它们将再次被覆盖。这几乎总是不可取的
有关更详细的讨论,请参见此问题:构造函数的
原型
是从构造函数创建的实例之间共享的对象
如果在构造函数中更新prototype
对象的属性,则共享该prototype对象的所有实例都将引用最新的更新
在您的代码中,您不会注意到差异,但它仍然是错误的。没有必要一直用新的相同版本覆盖原型函数
如果您的代码发生更改,以至于添加到原型中的函数引用构造函数中的局部变量,那么所有实例最终都将使用引用最新调用中变量的原型函数。这几乎不是你想要的
如果您的代码发生更改,从而覆盖构造函数的整个原型对象,则创建的每个实例都将引用不同的原型对象,并且您将无法通过向任务添加新方法来更新所有实例的原型。prototype
,因为它只是更新最新实例的prototype对象。应该可以回答您的问题(或者至少有助于理解差异)。每次调用构造函数时都会执行“inside”,因此您不希望将prototype方法定义放在其中。有胆量是JavaScript“类”的商标:P
@DCoder,我不这么认为。他询问如何将原型方法放在构造函数内部或外部;我看不出“this”是如何涉及的。@DCoder:在这种情况下,函数被分配给构造函数中的任务。prototype
,而不是this
。这是两种不同的情况。不是复制品,非常感谢。我想这就是我要找的。