Javascript,扩展ES6类设置器将继承getter [英] Javascript, extending ES6 class setter will inheriting getter

查看:80
本文介绍了Javascript,扩展ES6类设置器将继承getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,带有以下示例代码:



  class Base {构造函数(){this._val = 1} get val(){返回this._val}}类Xtnd扩展基数{set val(v){this._val = v}} let x = new Xtnd(); x.val = 5; console.log(x.val); //打印'undefined' 



实例 x 不会从 Base 类继承 get val()... 。照原样,Javascript将未使用getter的情况视为未定义的内容。



我遇到的情况是我有很多类都拥有一组完全相同的吸气剂,但具有独特的吸气剂。目前,我只是在每个类中复制吸气剂,但我正在重构并希望消除冗余代码。



有没有一种方法可以告诉JS阻止基类中的吸气剂,或者有人可以很好地解决这个问题?

解决方案

此限制是由于JavaScript如何处理后台的属性访问器而引起的。在ECMAScript 5中,最终得到的原型链具有 val 的nofollow noreferrer>属性描述符,其中包含由您的类定义的 get 方法,以及 set 方法未定义。



在您的 Xtnd 类中您还有一个 val 的属性描述符,它遮盖了基类 val 的整个属性描述符,其中包含一个<$ c该类定义的$ c> set 方法和一个未定义的 get 方法。



为了将吸气剂转发到基类实现,不幸的是,每个子类都需要一些样板,但您至少不必复制实现本身:



<前class = snippet-code-js lang-js prettyprint-override> class Base {Constructor(){this._val = 1} get val(){return this._val}} class Xtnd扩展了Base {get val(){return super.val} set val(v){this._val = v}} let x = new Xtnd(); x.val = 5; console.log(x.val); //打印 5


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?

解决方案

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'

这篇关于Javascript,扩展ES6类设置器将继承getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆