(可以进行编辑以获得更好的问题标题 - 很难表达我正在寻找的内容)
嗨,
我一直在使用原型(prototype),但最近发现需要在原型(prototype)中使用命名空间来对相关函数进行分组。该代码最简单的形式如下所示:
// Base grid functions.
Grid.prototype = {
init: function init() {
document.getElementById("output").innerHTML += "<br>" + this.id;
this.Rows.init();
this.Test.init();
document.getElementById("output").innerHTML += "<br><br>";
},
Test: {
init: function init() {
document.getElementById("output").innerHTML += "<br>" + this.id;
}
}
};
// Additional row-related and row utility functions.
Grid.prototype.Rows = {
init: function init() {
document.getElementById("output").innerHTML += "<br>" + this.id;
}
};
在我的Rows
“命名空间”,我想维护 this
的上下文因此开发人员可以调用类似 gridInstance.Rows.get()
的函数例如,无需每次都传递上下文(通过调用或应用)。
为此,我使用了 LoDash 的 _.bind
函数来设置我认为的每个新的上下文 Grid
每个与行相关的函数的实例。
注意 Test
“命名空间”纯粹是为了看看嵌套在 Grid
中时是否有效。原型(prototype),它会产生不同的结果。
var Grid = function Grid(id) {
var t = this;
// Assign an id to the control.
if (!id) {
// Assign a custom id if the control does not have one.
id = "grid-" + new Date().getTime();
}
t.id = id;
_.each(t.Rows, function (rowFn, key) {
t.Rows[key] = _.bind(rowFn, t);
});
_.each(t.Test, function (rowFn, key) {
t.Test[key] = _.bind(rowFn, t);
});
t.init();
};
有一个 fiddle here ,显示输出:
x x x
y x x
z x x
我的问题是,为什么Rows
原型(prototype)未实例化为新的(例如每次调用 Grid.prototype
时的 new Grid()
,我该如何解决这个问题?
其他想法
我的想法是 Grid.prototype
充当任何新的蓝图 Grid
实例,并且它将包含 namespace Rows
作为其中的一部分。
所以,在 Grid
构造函数,当我应用 this
的新上下文时至this.Rows
, this.Rows
最初是 Grid.prototype.Rows
的副本,而不是引用。蓝图,仅属于该实例。
在 Grid
构造函数,我想我会修改 this.Rows
,例如,绑定(bind)到 this
的上下文,而不是原型(prototype)本身。
发布答案
我的附加想法很愚蠢,因为我忘记了原型(prototype)是由继承它的所有对象引用的,而不是用作对象实例的蓝图。
fiddle here说明了这一点。
最佳答案
因为这就是原型(prototype)的用途:每个实例的所有成员都是相同的。
例如,您可以在 Grid init 函数中调用 this.Rows = Object.create(Grid.prototype.Rows);
,但您必须自己执行此操作。 JavaScript 不知道您需要为每个 Grid 实例创建一个新实例。
关于javascript - 为什么这些绑定(bind)函数的 "this"上下文在每个新实例中都相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359659/