[英]Why are local functions not possible in ES6 classes?
What was the idea about leaving out something like this in ES6: 在ES6中遗漏了类似的东西是什么想法:
class Foo {
myMethod(){
// do something with 'bar'
}
constructor(){
this.myMethod();
}
otherMethod(){
this.myMethod();
}
}
I know that it's possible to define the function in the constructor or outside the class and then use it with myMethod()
. 我知道可以在构造函数中或类外部定义函数,然后将其与
myMethod()
。 However coming from other languages I was surprised to see classes, but no local (or private) methods. 然而,来自其他语言我很惊讶地看到了类,但没有本地(或私有)方法。 I couldn't find anything on the internet about the reason why this was left out.
我在互联网上找不到关于这个被遗漏的原因。
EDIT: I just realized your post was about functions, not variables. 编辑:我刚刚意识到你的帖子是关于函数,而不是变量。 Since functions are a type of variable, all these solutions work for function even though I didn't explicitly make the examples functions
由于函数是一种变量,所有这些解决方案都适用于函数,即使我没有明确地生成示例函数
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());
Taking advantage of JS scoping to hide a variable, priv
behind a function 利用JS作用域隐藏变量,
priv
在函数后面
Pros: 优点:
Cons: 缺点:
class Foo2 { constructor(num) { Object.assign(this, { test() { return num; } }); } } var b = new Foo2(262); console.log(b.test());
Just what it says on the box. 正如它在盒子上所说的那样。
Pros: 优点:
Cons: 缺点:
class Foo3 { constructor(num) { this._eh = num; } test() { return this._eh; } } var c = new Foo3(101); console.log(c.test());
No need to hide behind strange security procedures. 无需隐藏在奇怪的安全程序背后。 Just specify in the name which properties are "private"
只需在名称中指定哪些属性为“私有”
Pros: 优点:
Cons: 缺点:
const eh = Symbol("eh"); class Foo4 { constructor(num) { this[eh] = num; } test() { return this[eh]; } } var d = new Foo4(100); console.log(d.test());
I just wanted to include this one because I thought it was cool 我只是想包括这个,因为我觉得它很酷
Pros: 优点:
Cons: 缺点:
Reflect.ownKeys()
Reflect.ownKeys()
访问所有键(包括符号Reflect.ownKeys()
Hope this was helpful! 希望这有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.