简体   繁体   English

在另一个JS文件中调用全局函数。 我如何获得“这个”的作用?

[英]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.

相关问题 如何从 js 文件上的一个 function 获取变量并将其用于另一个 js 文件上的另一个 function? - How do I get a variable from one function on a js file and use it for another function on another js file? 如何获得通过AJAX加载的JS文件识别的全局函数? - How do I get a global function recognized by my JS file loaded through AJAX? 我希望将 javascript 中该函数的函数名称和主体解析为一个单独的文件。 我如何使用 Java 做到这一点? - I want the function name and body of that function from a javascript to get parsed out into a separate file. How do I do that using Java? 我需要在.js文件,.html和.css文件之间传递的变量。 我该怎么做呢? - I need variables to pass between a .js file, an .html and a .css file. How do I do this? 如何让我的删除 function 在 Vue JS 中工作? - How do I get my delete function to work in Vue JS? 如何在另一个文件中调用 JS Function? - How do I call a JS Function in another file? 如何在POST中从另一个js文件调用函数? - How do I call a function from another js file in a POST? 如何访问一个不全局的函数,该函数存在于另一个js文件中? - How to access a function which is not global and it exist in another js file? 量角器打字稿在tsConfig文件中将ts转换为js文件时出现问题。 我该如何解决? - Protractor Typescript Problem converting ts to js file in tsConfig file. How do I fix this? 如何将get函数中的数据从node.js中的同一个js文件中的另一个函数中获取? - How can I get data from a get function to another function in the same js file in node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM