JavaScript,将public函数调用为public方法中的字符串,而不使用eval(显示模式) [英] 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;
/ **这是我试过的
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
是一个字符串文字。它没有调用
方法。 -
window [module。 privateMethod]('test')
将不起作用,因为首先,模块
没有属性privateMethod
。它不会是私人的。这意味着你试图调用
窗口[undefined]
,这不是一个功能。
I'm trying to call a private function inside the revealing pattern. This is my code:
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();
});
Someone could help me?
Thanks!
Make your private functions properties of an object?
var module = (function(){
var privateFuncs = {
privateMethod: function(val) {
console.log(val);
}
};
var publicMethod = function() {
var functionString = "privateMethod";
privateFuncs[functionString]('test');
};
return {
init: publicMethod
};
})();
Your other attempts both fail, for different reasons:
functionString.call('test')
will never work becausefunctionString
refers to a string literal. It doesn't have acall
method.window[module.privateMethod]('test')
won't work because firstly,module
doesn't have a propertyprivateMethod
. It wouldn't be "private" if it did. That means you're attempting to invokewindow[undefined]
, which is not a function.
这篇关于JavaScript,将public函数调用为public方法中的字符串,而不使用eval(显示模式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!