Could someone please explain to me why ‘this’ correctly works in the second example of setTimeout and not in the first example?
Below logs ‘undefined’
const object = {
message: 'Hello, World!',
logMessage() {
console.log(this.message); // What is logged?
}
};
setTimeout(object.logMessage, 1000);
Below logs ‘Hello World’
const object = {
message: 'Hello, World!',
logMessage() {
console.log(this.message); // What is logged?
}
};
setTimeout(() => {
object.logMessage()
}, 1000);
Also, is the code below logs 4.
var length = 4;
function callback() {
console.log(this.length); // What is logged?
}
const object = {
length: 5,
method(callback) {
callback();
}
};
object.method(callback, 1, 2);
This code logs 5
var length = 4;
function callback() {
console.log(this.length); // What is logged?
}
const object = {
length: 5,
method(callback) {
console.log(this.length);
}
};
object.method(callback, 1, 2);
Could someone explain the difference please?
I would expect same results and dont understand it.