【发布时间】:2018-03-20 06:10:30
【问题描述】:
好吧,我们有这个:
class Car {
constructor(name) {
this.kind = 'Car';
this.name = name;
}
printName() {
console.log('this.name');
}
}
我想做的是定义 printName,像这样:
class Car {
constructor(name) {
this.kind = 'Car';
this.name = name;
}
// we want to define printName using a different scope
// this syntax is close, but is *not* quite correct
printName: makePrintName(foo, bar, baz)
}
其中 makePrintName 是一个仿函数,如下所示:
exports.makePrintName = function(foo, bar, baz){
return function(){ ... }
};
这在 ES6 中可行吗?我的编辑器和 TypeScript 不喜欢这个
注意:使用 ES5,这很容易做到,看起来像这样:
var Car = function(){...};
Car.prototype.printName = makePrintName(foo, bar, baz);
使用类语法,目前最适合我的是:
const printName = makePrintName(foo,bar,baz);
class Car {
constructor(){...}
printName(){
return printName.apply(this,arguments);
}
}
但这并不理想。 如果你尝试使用类语法来做 ES5 语法可以做的事情,你会发现问题。因此,ES6 类包装器是一个泄漏抽象。
要查看实际用例,请参阅:
https://github.com/sumanjs/suman/blob/master/lib/test-suite-helpers/make-test-suite.ts#L171
使用TestBlock.prototype.startSuite = ... 的问题在于,在这种情况下,我不能简单地在线返回课程:
https://github.com/sumanjs/suman/blob/master/lib/test-suite-helpers/make-test-suite.ts#L67
【问题讨论】:
-
“注意,使用 ES5,这很容易做到” 你可以做同样的事情:ES6 - declare a prototype method on a class with an import statement
-
是的,但这是 ES6 比 ES5 更少动态和更严格的完美示例。导入语句的技术是 ES5 语法而不是 ES6 语法。
-
呃?所有在 ES5 中有效的东西在 ES6 中也有效。如果您指的是 ES6 中引入的语法,那当然。但是如果不使用 ES6 之前引入的语法,就无法编写 JavaScript 程序......所以这个论点有点愚蠢。
-
老兄,我不知道我们为什么要争论这个......这是 ES6 类的限制,简单明了。如果你是某个 JS 委员会的成员,请解决这个问题。
-
“使用TestBlock.prototype.startSuite = ...的问题是,在这种情况下,我不能简单地在线返回类”但是你不是必需的把return语句放在那里。声明后可以
return TestBlock;。
标签: javascript typescript ecmascript-6