繁体   English   中英

无法将“ this”绑定到导入的函数-JavaScript

[英]Can not bind 'this' to imported function - javascript

我是一个初学者,我想将'this'绑定到我从另一个文件导入的辅助函数(我可以使用在当前词法环境中创建的变量)。

但是我已经认识到,我可以将这些导入的函数绑定到我在文件中创建的任何对象(我在文件中创建的对象)中,但是不能绑定到当前对象。

node.js示例: https//github.com/sdeli/issues-with-this

 // random-js-file.js // this is the function I import in app.js function logOutThis() { console.log(this); } module.exports = logOutThis; // -------------------------------- // app.js const importedFn = require('./random-js-file.js'); // this is now the global of random-js-file.js importedFn(); console.log('--------------------------------'); var monkey = { chimp : 'chimp' } // this is now the object 'monkey' var myfunction = importedFn.bind(monkey); myfunction(); console.log('---------------------------------'); //this should be now the current this var myfunction2 = importedFn.bind(this); myfunction2(); // console.log displays '{}' and i can not refer to the variable in this lexical environment 

所以我不明白为什么我不能将'this'绑定到已导入的函数中,但可以将其绑定到任何对象。

谢谢你的建议

除非它显式导出所需的位(或提供公开这些位的功能),否则无法访问导入的模块的内部上下文。 使用Javascript this并不表现像Java this ,和模块并不类。

还有其他一些情况,但基本上,如果您当前使用的函数称为someFunc并且使用语法a.someFunc()进行调用,则this a.someFunc()将与a相同。 这是一个可行的示例:

const someObject = {
    someFunc() {
       //Here, "this" will be the same as someObject, because of the way we called it
       someOtherFunction();

    }
};

someObject.someFunc();

function someOtherFunc() {
    //"this" is still someObject because it's inherited from the calling function which was not called using a method syntax
    x.y(); //inside the y() function, "this" will now be x
}

恕我直言,基本上, this是Java语言中的一团糟,并且是我避免尽可能使用它的关键原因之一。 那意味着我不使用类,而我从闭包中得到了我需要的一切。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM