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?
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.
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.
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.
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.
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;
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With