0

I am very new to javascript programming, i am trying to understand how javascript program works. Hence i read about concepts like execution context, execution stacks etc. After understanding a bit of execution context i learned that "this" refers to execution context. So i tried to print execution context inside an object literal to check the execution context, hence i wrote the following code.

var obj = {
    method: function() {
        console.log(this);
    }
};
obj.method();

This gives me an output as:

{ method: [Function: method] }

After seeing this i have two questions, that is, is the above code correct to know the execution context?, and if yes, then shouldn't execution context should be an Object { method: function() } instead of the output it is giving.

I tried reading a lot regarding this but i couldn't crack it.

Ayush Mishra
  • 267
  • 3
  • 14
  • 1
    `this` (in this case) refers to the object that the method was called on (`obj`). The exact style of console output depends on your browser but `{ method: [Function: method] }` is the same thing as `Object { method: function() }`. – Đinh Carabus Apr 26 '20 at 08:33
  • 1
    there's no difference in what you are expecting and what you got as context. – AZ_ Apr 26 '20 at 08:37

2 Answers2

1

You are actually right.

this refers to the environment in which the JavaScript code is executed.

And you are also right about it being an object in your particular case.

var obj = {
  method: function() {
      console.log(typeof this);
  }
};
obj.method();

Run the snippet above, you will find the type of this as object.

That basically means that your environment (this) is an object, which contains a property called method which is a function.

There is much more to this than this.

Utsav Patel
  • 2,789
  • 1
  • 16
  • 26
1

In Chrome the output looks like

{method: ƒ}

Internet Explorer

[object Object]   {}

Firefox

Object { method: method() }

They all mean the same thing and refer to the object obj.

Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44