繁体   English   中英

Javascript ES6类语法模式

[英]Javascript es6 class syntax pattern

我正在开发一个节点模块,我想继续使用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称为函数,并且得到与将他的方法称为“ say”相同的结果。 基本上,man('text')产生与man.say('text')相同的效果; 如何使用es6类语法重新创建此模式?

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

最好不要使用该模式。

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

您可以执行类似于扩展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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM