Reputation: 23
i want to understand a little bit more about the javascript reference scope, i was trying to import a function from onother file like this
file1.js
exports.checkIfCan = function(){
//make some check
}
exports.calculate = function(){
this.checkIfCan();
}
and using the calculate method with this import
file2.js
const { calculate } = require('./file1.js')
calculate()
actually the error is this.checkIfCan is not a function
but if i import all the module like this it works
const calculation = require('./file1.js')
calculation.calculate();
I just wanna understand more about the global/local scope in javascript
Upvotes: 2
Views: 2351
Reputation: 905
@Vlad Vlads, your problem is in the use of keyword this in your file file file1.js.
In accordance to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this, following behaviour may happen:
The value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.
With that been said, if you remove the keyword this in your function, following will then works as expected:
const { calculate } = require('./file1.js')
calculate()
Your second example will also works as expected
const calculation = require('./file1.js')
calculation.calculate()
Upvotes: 0
Reputation: 1409
this
refers to the context of the function invocation, which in your case is undefined
(on browsers the default is window
).
Here's an example as simple as possible to make you understand it:
calculation.calculate(); // <= you are calling calculate from calculation, so 'this' is calculation
calculate(); // <= you are calling calculate from... nothing, so 'this' is undefined
Update: using arrow functions it would work either case because this
will be taken from the function's surrounding scope instead of the context, and in the top-level code in a Node module this
is equivalent to module.exports
.
There's a lot to explain about the this
in javascript, may I suggest you read the free ebook You Don't Know JS: this and Object prototypes? You'll find much more information there.
Upvotes: 2
Reputation: 21
You should use import instead:
file1.js
function abc() {}
export {
abc
}
file2.js
import { abc } from 'file1.js';
abc();
Upvotes: -1