In a javascript file, when I declare a function using function
keyword, I can placed my function after my caller function, something like
// test.js
function myCaller() {
foo('hello world'); // this works!
this.foo('hello world'); // this works!
}
function foo(text) {
console.log('foo called!', text);
}
myCaller()
but if I turned the foo
into an arrow function, and placed it at same position, then in myCaller
function, it said foo
is not defined, also it won't work if I use this
keyword to locate the foo
function, which I assume the this
refers to global/document level
// test.js
function myCaller() {
foo('hello world'); // es-lint warning: 'foo' was used before it was defined
this.foo('hello world'); // compilation error: foo is not defined
}
const foo = (text) => {
console.log('foo called!', text);
}
myCaller();
- I was wrong, I thought the 2nd approach without using this
does not work because of javascript compilation error of not defined
, but it was actully my eslint error - 'foo' was used before it was defined
, does it mean it's not recommend to do this way?
Why is that and does it mean we have to declare the arrow function always above caller
function? Is there any alternative way to solve that?
const foo = (text) => {
console.log('foo called!', text);
}
// test.js
function myCaller() {
foo('hello world'); // this works! no es-lint warning now
this.foo('hello world'); // no compilation error but there is a run-time error : 'this.foo is not a function'
}
myCaller();
In addition, I found when declare the arrow function inside a javascript class, it would work with this
keyword only with caller function being arrow function as well, if caller function is with function
keyword, this will not work...
// myTest.js
class myTest {
myCaller() {
foo('hello world'); // compilation error: foo is undefined
}
myCaller2 = () => {
this.foo('hello world'); //this works!
}
foo = (text) => {
console.log('foo called!', text);
}
}
new myTest().myCaller();
new myTest().myCaller2();