简体   繁体   中英

Can not bind 'this' to imported function - javascript

I am a beginner and I want to bind 'this' to helper-functions which I have imported from an other file (that I can use the variables, I created in the current lexical environment ).

But I have recognized, that I can bind these imported functions to any object - which I have created in the file, into I have imported them - but not to the current this.

node.js example: 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 

So I dont understand why I can not bind 'this' into a function which I have imported but I can bind it to any object.

Thank you for your suggestions

There isn't a way to access the inner context of an imported module unless it explicitly exports the bits you want (or provides functions that expose them). Javascript this doesn't behave like Java this , and modules aren't classes.

There's some other cases, but basically, if the function you're currently is called someFunc and it was called with syntax a.someFunc() , then this will be the same as a . Here's a worked example:

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
}

Basically, IMHO, this is a broken mess in Javascript and is one of the key reasons I avoided using it whereever possible. That means I don't use classes, and I get everything I need from closures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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