【问题标题】:Javascript es6 class syntax patternJavascript es6 类语法模式
【发布时间】:2016-11-10 21:02:04
【问题描述】:

我正在开发一个节点模块,我想继续使用 es6 类语法来保持样式一致性,但我发现这种模式无法重现:

const proto = module.exports = function(options) {
    man.opts = options || {};
    function man(sentence) {
        man.say(sentence);
    }

    man.__proto__ = proto;
    man.age = 29;
    man.say = function(sentence) {
        console.log(sentence);
    };
    return man;
};

这个函数的奇怪之处在于,我可以将它作为标准构造函数调用,并使用他的方法和道具获取 man,但我也可以将 man 作为函数调用,并获得与调用他的方法“say”相同的结果。 基本上 man('text') 产生与 man.say('text'); 相同的效果 如何使用 es6 类语法重新创建此模式?

【问题讨论】:

  • function cane(sentence)居然叫man!!!
  • 为了可维护性,除非你有充分的理由,否则不要这样做。
  • @GiovanniBruno 你可以简单地edit你的任务来修复错误
  • man.__proto__ = proto; 是一个非常非常奇怪的行。你为什么这样做?

标签: javascript class ecmascript-6


【解决方案1】:

基本上man('text')产生与man.say('text')相同的效果

最好不要使用那种模式。

如何使用 es6 类语法重新创建此模式?

你可以这样做类似于extending Function:

export default class {
    constructor(options) {
        const man = sentence => this.say(sentence);
        Object.setPrototypeOf(man, new.target.prototype);

        man.opts = options || {};
        man.age = 29;

        return man;
    }
    say(sentence) {
        console.log(sentence);
    }
}

【讨论】:

  • 明白,tnx!我将尝试重构我的 Express 分支以删除这种可怕的模式,但如果事情变得太难,我会尝试这种方式
猜你喜欢
  • 2016-07-25
  • 2019-08-22
  • 2018-01-15
  • 2017-09-12
  • 2018-09-19
  • 2016-07-04
  • 2016-10-11
  • 1970-01-01
  • 2016-12-19
相关资源
最近更新 更多