ES6类中的访问者组成

ES6类中的访问者组成

本文介绍了ES6类中的访问者组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 Thing 类,我想要可隐藏可打开的

Let's say I have a Thing class which I want to be both Hideable and Openable.

使用类似的方法,我已经能够从多个班级继承。

Using a similar approach to Douglas Crockford's object creation through composition, I have been able to "inherit" from multiple classes.

这种方法不起作用有访问者(getter / setter)。

我需要使用类,因为它是一个要求。我也发现我在从一个类到另一个类重复功能,但我不希望这些功能从基类继承。

I need to use classes as it's a requirement. I'm also finding that I am duplicating functionality from class to class, but I don't want these to inherit from a base class.

任何想法?

到目前为止我所取得的进展如下:

The progress I have made so far is in the below snippet:

class Openable {

  constructor(isOpen = false) {
    this._isOpen = isOpen;
  }

  get isOpen() {
    return this._isOpen + ' is stupid.';
  }

  set isOpen(value) {
    this._isOpen = value;
  }

}


class Hideable {

  constructor(isHidden = false) {
    this._isHidden = isHidden;
  }

  get isHidden() {
    return this._isHidden + ' is stupid.';
  }

  set isHidden(value) {
    this._isHidden = value;
  }

}


class Thing {

  constructor(config) {
    let { isOpen, isHidden } = config;

    let openable = new Openable(isOpen);
    this.isOpen = openable.isOpen;

    let hideable = new Hideable(isHidden);
    this.isHidden = openable.isHidden;
  }

}


let thing = new Thing({
  isOpen: true,
  isHidden: false
});

推荐答案

因为 isOpen isHidden 访问者,你不能只是获取它们的副本,你必须在需要时访问它们。

Because isOpen and isHidden are accessors, you can't just grab a copy of them, you have to access them when you want them.

仍然,你可以创建你的拥有 isOpen isHidden 使用底层的:

Still, you can create your own isOpen, isHidden which use the underlying ones:

let openable = new Openable(isOpen);
Object.defineProperty(this, "isOpen", {
    get: () => openable.isOpen,
    set: value => {
        openable.isOpen = value;
    }
});

let hideable = new Hideable(isHidden);
Object.defineProperty(this, "isHidden", {
    get: () => hideable.isHidden,
    set: value => {
        hideable.isHidden = value;
    }
});

当然,如果你经常这样做,你想要一个工人函数来设置而不是一直重新输入它:

Naturally, if you do this a lot, you'd want to have a worker function to set that up rather than retyping it all the time:

function wrapProperty(dest, src, name) {
    Object.defineProperty(dest, name, {
        get: () => src[name],
        set: value => { src[name] = value; }
    });
}

(或通过抓取属性描述符并更新它来实现)

然后:

wrapProperty(this, openable, "isOpen");
wrapProperty(this, hideable, "isHidden");






我质疑你必须使用 可打开可隐藏。它们看起来更像是我的混合物。


I'd question the requirement that you must use class for Openable and Hideable. They look much more like mixins to me.

这篇关于ES6类中的访问者组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:50