const obj = {
length:10,
log() {
console.log(this.length)
}
}
obj.log() // 10
const length = 20
const fn = obj.log
fn() // 0
const arr = [30,obj.log]
arr[1]() // 2
Why the fn() result is 0 ? if use var length = 20 instead of const length = 20 the result is 20, how this happening?
the differences lies in what this means in the context of execution of the function log
in the first case this = obj so this.lenght = 10
in the second case this is the window object in the browser so if you use var or if you write window.length it returns the value you set
in the third case this means the array so it returns the array length
const obj = {
length:10,
log() {
console.log(this.length)
}
}
obj.log() // 10
const length = 20
const fn = obj.log
fn() // 0
window.length = 20
fn() // 20
const arr = [30,obj.log]
arr[1]() // 2