![](/img/trans.png)
[英]How to call a public method of one JS module into another, using the Revealing Module Pattern?
[英]JavaScript, call private function as a string inside public method without using eval (Revealing pattern)
我试图在揭示模式中调用私有函数。 这是我的代码:
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();
});
有人可以帮帮我吗?
谢谢!
创建对象的私有函数属性?
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
。 如果它这样做,它就不会是“私人的”。 这意味着您正在尝试调用window[undefined]
,这不是一个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.