Jump to content

this value in object method creating with object literal vs ES6 class syntax


Raktim

Recommended Posts

I'm asking about the 'this' binding in the arrow function of an object created by object literal syntax vs ES6 class syntax. 

Case 1: Object literal

const obj = {
     method: ()=>{
       console.log(this)
   }
}
obj.method();

Output

Window {window: Window, self: Window, document: document, name: "result", location: Location, …}

Case 2: ES6 class syntax

class obj{
  method = ()=>{
      console.log(this);
  }
}
(new obj).method();

Output

obj {method: ƒ}


I know arrow functions do not bind their own this, instead, they inherit the one from the parent scope then Why the result is different on the above two cases. 

Thanks in advance. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...