3

According to my understanding, the code below should output undefined when I call hi() but instead it logs a number. I'm using chrome. Can somebody elaborate why is this happening? Thanks in advance.

Screen shot of Code:

enter image description here

const obj = {
  name: "abc",
  sayHi: function() {
    console.log(this.name)
  }
}

obj.sayHi();
let hi = obj.sayHi;
hi();
Shidersz
  • 16,846
  • 2
  • 23
  • 48
aaKhan
  • 247
  • 2
  • 16
  • This is the classic problem everyone faces while learning js. This problem arises due to the context of `this` for js `function` syntax. Try googling js normal function vs arrow functions. – A Rogue Otaku Jun 03 '19 at 20:34
  • Can't reproduct this, it works for me. Value is undefined as it should be – Isaac Vidrine Jun 03 '19 at 20:34
  • 5
    You're not using strict mode, so `this.name` is `window.name` which is not undefined if you run it in a browser window. If you add `"use strict";` as the first line of your function, you will get an error: `TypeError: Cannot read property 'name' of undefined`, since `this` is `undefined`. – Paul Jun 03 '19 at 20:35
  • 2
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Heretic Monkey Jun 03 '19 at 20:55
  • Thanks, I found the answer. The window object already had a variable ```name``` that's why it was outputting that number. But I still don't understand one thing. Usually the code inside chrome runs in strict mode, while learning the about ```this```, I used the console to confirm this. And if that was the case, ```this``` should not be pointing to global object but undefined instead. – aaKhan Jun 03 '19 at 21:03
  • 2
    @aaKhan JavaScript is not in strict mode unless you `"use strict"` or the code is part of a class. – Paul Jun 03 '19 at 21:06

1 Answers1

0

When you call obj.sayHi(), this refers to obj.

When you call hi(), this refers to the window object.

If you want this to be undefined, you'll need to use "use strict";.

If you want this to be obj, you can bind the function to obj.

Demo

"use strict"

const obj = {
  name: "abc",
  sayHi: function() {
    console.log(this)
  }
}

obj.sayHi();

let hi1 = obj.sayHi;
hi1();


let hi2 = obj.sayHi.bind(obj);
hi2();
John Slegers
  • 45,213
  • 22
  • 199
  • 169