0

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?

user956609
  • 906
  • 7
  • 22
  • 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. – jarmod May 18 '22 at 14:02
  • 1
    Required reading: [How does the "this" keyword work?](https://stackoverflow.com/q/3127429) – VLAZ May 18 '22 at 14:04
  • @jarmod what's the difference? – user956609 May 18 '22 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?](https://stackoverflow.com/q/28776079) – VLAZ May 18 '22 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. – jarmod May 18 '22 at 14:09
  • @jarmod why the logged output is 0? what's the return value of called function? – user956609 May 18 '22 at 14:23
  • In the `const length = 20` variant, the call to `fn()` logs `window.length` because `this` is actually `window` when run in a browser (and it's `global` when run in Node.js), whatever value that is. In your case, it's zero. I just ran this in the Chrome debugger and it logged 2 (which is the value of `window.length`). Modify your obj.log function to also log the value of `this`. You'll see that it changes from the `obj` object to window/global. And read the links that @VLAZ offered earlier. – jarmod May 18 '22 at 15:23
  • @jarmod. what... you logged 2? – user956609 May 19 '22 at 00:18
  • Yes, it logged 2. The `this` object in that scenario is `window` and its length property is 2. – jarmod May 19 '22 at 01:41

1 Answers1

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
R4ncid
  • 6,944
  • 1
  • 4
  • 18