[英]How to call a function already defined using javascript closure
我有一个javascript文件,我正在使用闭包创建函数:
"use strict";
(function(window) {
var ele = function() {
return {
func3:function(methodToCall){
methodToCall();
},
func1:function() {
this.func2();
},
func2:function() {
}
}
}
window.ele = new ele();
})(window);
如您所见,我正在尝试从func1内部调用func2。 浏览器对我咆哮说“ func2未定义”。 我这样称呼func1:
<script>
ele.func3(ele.func1());
</script>
如何从func1调用func2? 谢谢
当您执行methodToCall()时,它与window.methodToCall()相同。 因此,当func1运行时,它引用的是窗口对象,而不是您真正想要的对象。 解决它的一种方法是手动绑定范围,如下所示:
methodToCall.bind(this)();
这样,此引用将传递给func1而不是window,它将起作用
你有没有做这个工作? 这是范围和关闭的问题。 您可以在此处获得有关使用闭包的许多详细信息: https : //stackoverflow.com/a/111111/6441528
此外,这是一小段代码,应通过描述直接回答您的问题:
function ClosureObject() {
var _this = this;
this.interior1 = function() {
console.log('** in interior 1');
var callingOtherFunction = _this.interior2();
console.log('** return from other function in closure', callingOtherFunction);
}
this.interior2 = function() {
return "returning from interior2";
}
}
基本上,通过使用“ this”在函数内部声明作用域,可以访问闭包内的其他函数。 这应该允许您执行以下操作:
var foo = new ClosureObject();
foo.interior1();
那会输出** return from other function in closure returning from interior2
到您的控制台。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.