[英]Why are local functions not possible in ES6 classes?
在ES6中遗漏了类似的东西是什么想法:
class Foo {
myMethod(){
// do something with 'bar'
}
constructor(){
this.myMethod();
}
otherMethod(){
this.myMethod();
}
}
我知道可以在构造函数中或类外部定义函数,然后将其与myMethod()
。 然而,来自其他语言我很惊讶地看到了类,但没有本地(或私有)方法。 我在互联网上找不到关于这个被遗漏的原因。
编辑:我刚刚意识到你的帖子是关于函数,而不是变量。 由于函数是一种变量,所有这些解决方案都适用于函数,即使我没有明确地生成示例函数
var Foo = (function() { let priv = { "eh": 0 }; return class Foo { constructor(num) { priv.eh = num; } test() { return priv.eh; } }; })(); var a = new Foo(383); console.log(a.test());
利用JS作用域隐藏变量, priv
在函数后面
优点:
缺点:
class Foo2 { constructor(num) { Object.assign(this, { test() { return num; } }); } } var b = new Foo2(262); console.log(b.test());
正如它在盒子上所说的那样。
优点:
缺点:
class Foo3 { constructor(num) { this._eh = num; } test() { return this._eh; } } var c = new Foo3(101); console.log(c.test());
无需隐藏在奇怪的安全程序背后。 只需在名称中指定哪些属性为“私有”
优点:
缺点:
const eh = Symbol("eh"); class Foo4 { constructor(num) { this[eh] = num; } test() { return this[eh]; } } var d = new Foo4(100); console.log(d.test());
我只是想包括这个,因为我觉得它很酷
优点:
缺点:
Reflect.ownKeys()
访问所有键(包括符号Reflect.ownKeys()
希望这有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.