基本上我正在尝试做的是为匿名函数提供对“私有(private)”函数/变量的访问。我需要对我实现此目标的两种方式以及这些方法的可能更好替代方案提出一些意见。 Fiddle
观察以下片段。
function Something()
{
/*private*/ var _someVariable = 1;
/*private*/ function _someFunction() {
alert('_someFunction');
}
/*public*/this.SomeDelegate1 = function(codeblock) {
var members = $.extend({
_someVariable : _someVariable,
_someFunction:_someFunction
}, this);
codeblock.apply(members);
}
/*public*/this.SomeDelegate2 = function(codeblock) {
var caller = eval('(' + codeblock + ')');
caller.apply(this);
}
}
在 SomeDelegate1 中,我将私有(private)成员转换为实例成员并将其作为上下文传递给 如下所示的匿名函数。
var someInstance = new Something();
someInstance.SomeDelegate1(
function() {
this._someFunction();
alert(this._someVariable);
}
);
我喜欢这样一个事实,即可以指定您想公开哪些成员,但它可能会变得非常笨拙,例如例如,当您需要更新“私有(private)”变量时。
我显然可以将所有成员都写成实例成员,但我更希望它们保持“私有(private)”状态,只允许在回调函数的范围内进行访问。
在 SomeDelegate2 中,我使用了一个 eval(是的,我知道与此相关的所有邪恶和巫术)。
var someInstance = new Something();
someInstance.SomeDelegate2(
function() {
_someFunction();
alert(_someVariable);
}
);
由于我将代码注入(inject)到函数中,“私有(private)”作用域成员自动可用,因此我不需要对成员等进行任何复制,否则不需要做很多工作。
这种方法是否存在根本问题?
您是否有更好的替代方案/方法来实现这一目标?
最佳答案
正如我在评论中所说,我会将所有内容公开并在“私有(private)”属性名称前加上下划线。这就是我重组您的代码的方式:
function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
var Something = defclass({
constructor: function () {
this._someVariable = 1;
},
_someFunction: function () {
alert("someFunction");
},
someDelegate1: function (f) {
f.apply(this);
},
someDelegate2: function (f) {
f.call(this, this._someVariable, this._someFunction);
}
});
var someInstance = new Something;
someInstance.someDelegate1(function () {
this._someFunction();
alert(this._someVariable);
});
someInstance.someDelegate2(function (someVariable, someFunction) {
someFunction();
alert(someVariable);
});
不过这只是我的看法。我真的不明白拥有私有(private)变量的意义。即使有人弄乱了您的私有(private)变量,那也是他们的问题而不是您的问题。它会破坏他们的代码,而不是你的。
关于javascript - 在作用域外的匿名函数中访问 "private"成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502406/