-1

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?

9
  • In case it's not clear, you're referring to the value that is written by console.log, rather than the return value from the function. Commented May 18, 2022 at 14:02
  • 1
    Required reading: How does the "this" keyword work? Commented May 18, 2022 at 14:04
  • @jarmod what's the difference? Commented May 18, 2022 at 14:07
  • 1
    "if use var length = 20 instead of const length = 20 the result is 20, how this happening?" Do let statements create properties on the global object? Commented May 18, 2022 at 14:07
  • 1
    I'm saying that your use of the word "result" is ambiguous and some readers may initially think you are referring to the return value of the called function rather than its logged output. I'm simply clarifying what you (presumably) mean. Commented May 18, 2022 at 14:09

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

how 0 output from that log?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.