I am struggling with the this
keyword. I am comparing the value of this
within a declared function vs within an expression function.
// Declared function
function declaredFunction() { console.log(this); }
// Expression function
var expressionFunction = (() => { console.log(this); }) ;
I define the two of them in a this.js
file and run it with a simple node this.js
command.
declaredFunction();
expressionFunction();
declaredFunction()
logs the global
object in the console :
Object [global] {
global: [Circular],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout] { [Symbol(util.promisify.custom)]: [Function] },
queueMicrotask: [Function: queueMicrotask],
clearImmediate: [Function: clearImmediate],
setImmediate: [Function: setImmediate] {
[Symbol(util.promisify.custom)]: [Function]
}
}
expressionFunction()
just logs {}
.
Two questions :
- What is
{}
(an empty object, obviously, but I don't understand what it is from a semantic point of view); and - Why doesn't my
expressionFunction()
log theglobal
object too?
There is definitely something I don't understand here about how declaring a function differs from assigning a function expression to a variable.