Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call a super setter in ES6 inherited classes?

Tags:

I'm wondering if the following is in compliance with the ES6 spec:

class X {   constructor(name) {     this._name = name;   }    get name() {     return this._name;   }    set name(name) {     this._name = name + "X";   } }  class Y extends X {   constructor(name) {     super(name);   }    set name(name) {     super.name = name;     this._name += "Y";   } } 

The idea is that let y = new Y(""); y.name = "hi" should result in y.name === "hiXY" being true.

As far as I can tell, this doesn't work in Chrome with the ES6 flag turned on. It also doesn't work using Babel with the es2015 flag. Is using super.name = ... in an inherited setter not part of the ES6 spec? Or is this a bug in the implementation of Babel?

like image 201
TAGraves Avatar asked Dec 24 '15 17:12

TAGraves


People also ask

Why call super in constructor JavaScript?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods. Tip: To understand the "inheritance" concept (parent and child classes) better, read our JavaScript Classes Tutorial.

How is inheritance implemented in ES6?

We use the extends keyword to implement the inheritance in ES6. The class to be extended is called a base class or parent class. The class that extends the base class or parent class is called the derived class or child class.

What does Super do in typescript?

The super keyword can be used in expressions to reference base class properties and the base class constructor. Super calls consist of the keyword super followed by an argument list enclosed in parentheses. Super calls are only permitted in constructors of derived classes.

What is a derived class in JS?

In JavaScript, there's a distinction between a constructor function of an inheriting class (so-called “derived constructor”) and other functions. A derived constructor has a special internal property [[ConstructorKind]]:"derived" .


1 Answers

class Y extends X {   constructor(name) {     super(name);   }    set name(name) {     super.name = name;     this._name += "Y";   } } 

will override the name properly with an accessor for just the setter, with no getter. That means your y.name === "hiXY" will fail because y.name will return undefined because there is no getter for name. You need:

class Y extends X {   constructor(name) {     super(name);   }    get name(){     return super.name;   }    set name(name) {     super.name = name;     this._name += "Y";   } } 
like image 99
loganfsmyth Avatar answered Oct 25 '22 16:10

loganfsmyth