Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do `var self = this` inside es6 class?

I am running the below code in nodejs

this.x = 'global x'; class Point {     constructor(x) {         this.x = x;     }     toString() {         return this.x;     } } var obj = new Point(1); obj.toString();// 1 as expected var a = obj.toString;// Here I can do something like var a = obj.toString.bind(obj); to get rid of the situation. But I am curious to know how can we write `var self = this`; a();// TypeError: Cannot read property 'x' of undefined 

a(); throws the error.
How can we do like var self = this; as we used to do in es5 to prevent such a situation?

like image 746
intekhab Avatar asked Sep 15 '15 10:09

intekhab


People also ask

How do I create an instance of a class in ES6?

Creating Objects To create an instance of the class, use the new keyword followed by the class name. Following is the syntax for the same. Where, The new keyword is responsible for instantiation.

What is self variable in JavaScript?

Actually self is a reference to window ( window. self ) therefore when you say var self = 'something' you override a window reference to itself - because self exist in window object.

Is JavaScript ES6 OOP?

ES6(ECMAScript2015) is a major upgrade to JavaScript. In this article we will learn the new way of achieving Object Oriented concepts like class, object, static properties, constructor and inheritance with super and extends in JavaScript.

What is ES6 class in JavaScript?

There are two types of Class in ES6: parent class/super class: The class extended to create new class are know as a parent class or super class. child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor.


1 Answers

How can we do like var self = this; as we used to do in ES5?

You can do it exactly like you did in ES5 - ES6 is completely backward-compatible after all:

class Point {     constructor(x) {         this.x = x;         var self = this;         this.toString = function() {             return self.x;         };     } } 

However, that's really not idiomatic ES6 (not talking about const instead of var). You'd rather use an arrow function that has a lexical-scoped this, so that you can avoid this self variable completely:

class Point {     constructor(x) {         this.x = x;         this.toString = () => {             return this.x;         };     } } 

(which could even be shortened to this.toString = () => this.x;)

like image 140
Bergi Avatar answered Sep 19 '22 00:09

Bergi