我试图在显示模式中调用一个私有(private)函数。这是我的代码:
var module = (function(){
var privateMethod = function(val) {
console.log(val);
}
var publicMethod = function() {
var functionString = "privateMethod";
/** This what I tried
functionString.call('test');
window[module.privateMethod]('test');
*/
}
return {
init: publicMethod
}
})();
$(document).ready(function(){
module.init();
});
有人可以帮助我吗?
谢谢!
最佳答案
将对象的私有(private)函数属性设为对象?
var module = (function(){
var privateFuncs = {
privateMethod: function(val) {
console.log(val);
}
};
var publicMethod = function() {
var functionString = "privateMethod";
privateFuncs[functionString]('test');
};
return {
init: publicMethod
};
})();
由于不同的原因,您的其他尝试都失败了:
functionString.call('test')
永远不会工作,因为functionString
指的是字符串文字。它没有call
方法。window[module.privateMethod]('test')
将不起作用,因为首先,module
没有属性privateMethod
。如果这样做,它就不会是“私有(private)的”。这意味着您正在尝试调用window[undefined]
,这不是函数。
关于JavaScript,在不使用 eval 的情况下将私有(private)函数作为公共(public)方法中的字符串调用(显示模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17294443/