The following code snippet is part of an exercise in which I need to guess the output of the code:
let length = 4;
function callback(){
console.log(this.length);
}
const object = {
length: 5,
method(callback){
callback();
},
};
object.method(callback, 1, 2);
The following code snippet is part of an exercise in which I need to guess the output of the code:
let length = 4;
function callback(){
console.log(this.length);
}
const object = {
length: 5,
method(callback){
callback();
},
};
object.method(callback, 1, 2);
From what I understood so far, the following is the process going on behind the scenes:
From the current understanding:
--> line 11: callback
definition is passed as arg
.
--> line 7: callback
definition is used as input for param
.
--> line 8: callback
keyword is called.
--> line 11: callback()
defined on line 2 is executed as a function with global scope.
--> line 3: this.length
refers to window.length
and output = 0
is obtained.
--> And the args
1
and 2
are irrelevant.
Please help me verify if the above explanation is correct or not. Thank you!
Share Improve this question asked yesterday SteveSteve 452 silver badges6 bronze badges 1 |1 Answer
Reset to default 1It looks like the issue here is this
related.
In non-strict mode, this
inside callback()
points to the global window
object, making this.length
equal to window.length
, which is usually 0
.
When you call callback()
directly inside method
, you’re not invoking it as a method of any object. In non-strict mode, a standalone function call defaults this
to the global object → window
.
The global let length = 4;
does not define length
as a property on window
, it simply declares a block-scoped variable in the global scope. Therefore, it does not affect this.length
.
The extra arguments (1, 2)
are ignored because method
only takes one parameter (callback
) and does nothing with those arguments.
EDIT 1 :
window.length
represents the number of frames (sub-browsing contexts). As you don’t have any iframes, window.length
is 0
. So the log statement ends up printing 0
.
Example of working code :
function callback() {
console.log(this.length);
}
const object = {
length: 5,
method(cb) {
// Force 'this' to be 'object'
cb.call(this);
},
};
object.method(callback, 1, 2);
callback()
function, not its "definition". – Pointy Commented yesterday