[英]Javascript es6 class syntax pattern
I'm working on a node module and i would like to keep using es6 classes syntax for style consistency but i found this pattern that I can't reproduce: 我正在开发一个节点模块,我想继续使用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;
};
The strange thing of this function is that I can call it as a standard constructor and get a man with his methods and props but I can also call man as a function and get the same result as calling his method "say". 该函数的奇怪之处在于,我可以将其称为标准构造函数,并让一个人知道他的方法和道具,但是我也可以将man称为函数,并且得到与将他的方法称为“ say”相同的结果。 Basically man('text') produces the same effect of man.say('text'); 基本上,man('text')产生与man.say('text')相同的效果; How can I recreate this pattern using es6 classes syntax? 如何使用es6类语法重新创建此模式?
Basically
man('text')
produces the same effect ofman.say('text')
基本上man('text')
产生与man.say('text')
相同的效果
Best don't use that pattern at all. 最好不要使用该模式。
How can I recreate this pattern using es6 classes syntax? 如何使用es6类语法重新创建此模式?
You can do it similar to extending Function
: 您可以执行类似于扩展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.