ES6类文字中的IIFE [英] IIFE in ES6 class literal
本文介绍了ES6类文字中的IIFE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ES5中,我们所有人都可以这样做:
In ES5 we all could do like this:
myClass.prototype.myMethod = (function () {return function() {}})();
我可以用ES6类文字做同样的技巧吗?
Am I able to do the same trick with ES6 class literals?
推荐答案
否,至少尚未. ES6类仅支持声明方法,因此任何非直接方法的东西(包括间接评估方法的东西,例如IIFE)都必须与原型一起声明.
No, not yet at least. ES6 classes only have support for declaring methods, so anything that's not directly a method (this includes things that indirectly evaluate to a method, such as IIFE) must still be declared with the prototype.
但是,ES6类的工作原理实际上与ES5构造函数相同,只是语法更加简洁,因此您仍然可以这样做:
However, ES6 classes really work the same as ES5 constructor functions do, only with a bit cleaner syntax, so you can still do this:
class MyClass {
constructor() {
/* initialize */
}
regularMethod() {
/* some stuff */
}
}
MyClass.prototype.myMethod = (function() { return function() })()
这等效于此:
function MyClass() {
/* initialize */
}
MyClass.prototype.regularMethod = function() {
/* some stuff */
}
MyClass.prototype.myMethod = (function() { return function() })()
这篇关于ES6类文字中的IIFE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文