[英]Calling a global function in another JS file. How do I get 'this' to work?
I have 2 js files: 我有2个js文件:
file1.js contains prototype A with: file1.js包含具有以下内容的原型A:
printname: function() {
console.log('my name is A');
}
getname: function() {
console.log('getting name..');
this.printname();
}
Then I put 'getname' function in a global variable because I want to access it anywhere: 然后,将“ getname”函数放在全局变量中,因为我想在任何地方访问它:
globalvar.myfunction = this.getname;
file2.js contains prototype B with: file2.js包含具有以下内容的原型B:
runmyglobalfunction: function() {
globalvar.myfunction();
}
When I call this.runmyglobalfunction, the result is: 当我调用this.runmyglobalfunction时,结果是:
I can see console log 'getting name..'. 我可以看到控制台日志“获取名称..”。
But I can't see 'my name is A' 但我看不到“我的名字是A”
How do I fix this? 我该如何解决?
You can .bind
the function's this
value to a specific value: 您可以将函数的
this
值.bind
到特定值:
globalvar.myfunction = this.getname.bind(this);
Now, no matter how globalvar.myfunction
is called, this
inside the function will always refer to what this
referred to in that line. 现在,无论多么
globalvar.myfunction
被调用时, this
函数内总是会参考一下this
简称在该行。
Related: How to access the correct `this` inside a callback? 相关: 如何在回调中访问正确的`this`?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.