Javascript, extending ES6 class setter will inheriting getter

僤鯓⒐⒋嵵緔 提交于 2020-06-06 08:08:31

问题


In Javascript, with the following illustration code:

class Base {
   constructor() {  this._val = 1   }
   get val()     { return this._val }
}

class Xtnd extends Base {
   set val(v)    { this._val = v }
}

let x = new Xtnd();
x.val = 5;
console.log(x.val);  // prints 'undefined'

the instance x will not inherit get val()... from Base class. As it is, Javascript treat the absence of a getter, in the presence of the setter, as undefined.

I have a situation in which I have many classes that all have the exact same set of getters but unique setters. Currently, I simply replicate the getters in each class, but I'm refactoring and want to eliminate the redundant code.

Is there a way to tell JS to keep the getter from the base class, or does anyone have an elegant solution to this problem?


回答1:


This limitation is due to how JavaScript treats property accessors behind the scenes. In ECMAScript 5, you end up with a prototype chain that has a property descriptor for val with a get method defined by your class, and a set method that is undefined.

In your Xtnd class you have another property descriptor for val that shadows the entire property descriptor for the base class's val, containing a set method defined by the class and a get method that is undefined.

In order to forward the getter to the base class implementation, you'll need some boilerplate in each subclass unfortunately, but you won't have to replicate the implementation itself at least:

class Base {
   constructor() {  this._val = 1   }
   get val()     { return this._val }
}

class Xtnd extends Base {
   get val()     { return super.val }
   set val(v)    { this._val = v }
}

let x = new Xtnd();
x.val = 5;
console.log(x.val);  // prints '5'


来源:https://stackoverflow.com/questions/53584705/javascript-extending-es6-class-setter-will-inheriting-getter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!