在 JavaScript 中通过字符串调用函数并保持在作用域内
我一直在玩耍和搜索,但我无法弄清楚这一点。我在 JavaScript 对象中有一个伪私有函数,需要通过 eval 调用(因为函数的名称是动态构建的)。但是,该函数通过闭包隐藏在全局范围内,我无法弄清楚如何使用 eval() 引用它。
例如:
var myObject = function(){
var privateFunctionNeedsToBeCalled = function() {
alert('gets here');
};
return {
publicFunction: function(firstPart, SecondPart) {
var functionCallString = firstPart + secondPart + '()';
eval(functionCallString);
}
}
}();
myObject.publicFunction('privateFunctionNeeds', 'ToBeCalled');
我知道这个例子看起来很傻,但我想保持简单。有什么想法吗?
I've been playing around and searching a bit, but I can't figure this out. I have a pseudo private function within a JavaScript object that needs to get called via eval (because the name of the function is built dynamically). However, the function is hidden from the global scope by a closure and I cannot figure out how to reference it using eval().
Ex:
var myObject = function(){
var privateFunctionNeedsToBeCalled = function() {
alert('gets here');
};
return {
publicFunction: function(firstPart, SecondPart) {
var functionCallString = firstPart + secondPart + '()';
eval(functionCallString);
}
}
}();
myObject.publicFunction('privateFunctionNeeds', 'ToBeCalled');
I know the example looks silly but I wanted to keep it simple. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
传递给
eval()
的字符串在 eval() 的范围内进行计算,因此您可以这样做但是,更好的解决方案是完全避免使用 eval() :
The string passed to
eval()
is evaluated in that eval()'s scope, so you could doHowever, a better solution would be to avoid the use of eval() entirely: