[英]Calling a outer function from within a closure in javascript
I have function defined as main which has a function inside say hit() 我有定义为main的函数,里面有一个函数hit()
(function main(){
var player1=new player();
function hit(){
//some code
}
})();
This belongs to file main.js 这属于文件main.js
I have another function player() in player.js which is called using the constructor at main.js 我在player.js中有另一个函数player(),它是使用main.js的构造函数调用的
function player(){
setTimeout(function(){
hit(); //cannot call hit
}, 1500);
}
I want to call the hit() function in main.js from player.js, but I cannot do so as I get a undefined error. 我想从player.js调用main.js中的hit()函数,但由于出现未定义的错误而无法执行。 Isn't main.js completely accessible from player.js due to closure property
由于闭包属性,无法从player.js完全访问main.js
The way I include this files is: 我包含此文件的方式是:
<script src='player.js'></script>
<script src='main.js'></script>
Thanks 谢谢
hit
won't be accessible outside the closure. 在封闭外部无法访问
hit
。 If you want it to expose globally , you will have to do something like: 如果要使其在全局范围内公开,则必须执行以下操作:
//get hold of the global object
var global= (function(){
return this;
})();
(function main(){
var player1=new player();
global.hit= function(){
//some code
};
})();
This is what I did and it seem to work for me 这是我所做的,似乎对我有用
var mainObj=new main();
function main(){
var player1=new player();
var this.hit=hit;
function hit(){
//some code
}
}
function player(){
mainObj.hit();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.