0

I'm trying to learn the 'this' concept in Javascript.
I have this simple code snippet:

sayHi = function(){
    console.log('hi');
    console.log(this);
}

class Test{
    constructor(){
        console.log(this);
    }
    instanceFunction(){
        sayHi();
    }
}

let ob = new Test();
ob.instanceFunction();

Output is:

Test {}
hi
[Global Object in Node]

May be I'm missing something basic, but I was expecting the third line in the output to be Test {} instead of [Global Object in Node]. How come the third line is the Global object, when invoked with an instance of Test class ?

Boney
  • 2,072
  • 3
  • 18
  • 23
  • Because `this` inside a function refers by default to `window` or the global object...? It doesn't matter *when or where it is invoked*, but *how it is invoked*, whether attached to an object or instance. – Andrew Li May 12 '17 at 03:17
  • maybe change `sayHi()` to `sayHi.call(this)` – Isaac May 12 '17 at 03:18
  • 3
    [`this` in JS](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this). *"when invoked with an instance of Test class ?"* - It isn't invoked *with* an instance of `Test`, it is invoked *from* an instance of `Test`. Not the same thing. – nnnnnn May 12 '17 at 03:24
  • Thanks @nnnnnn. I get it now. – Boney May 12 '17 at 03:59

0 Answers0