在 ES6 中是否允许解构 Class 实例属性?
In ES6 is destructuring Class Instance properties permitted?
假设我有以下代码:
class Foo {
constructor() {
this.a = 1;
this.b = 'something';
}
someMethod() {
// Is this legal?
let { a, b } = this;
}
}
someMethod
中的解构赋值合法吗?
我的直觉是它很好,但我在任何文档中都没有看到这种用法的参考。它目前在 Babel 中工作,但大概是因为在幕后 Babel 正在将 class 转换为一个函数。我的理解是(几乎)JS 中的所有内容都原型继承自 Object,因此我可能希望这对于 Classes 和 Class 实例也是如此。
我所看到的关于引擎盖下发生的事情的唯一参考 is here and specifies that the JS engine calls the internal method ToObject
which will only throw a TypeError when it encounters null
or undefined
. But the ToObject
docs 没有明确提及 class 个实例。
解构对象是明确允许的,并且是一项功能。
this
仅仅指一个对象。没什么特别的。
只要 this
指的是一个对象,这绝对没问题。 *
* this
可能 而不是 引用对象,具体取决于您如何调用 someMethod
,例如Foo.someMethod.apply(null)
。但无论如何你真的有更大的问题。
假设我有以下代码:
class Foo {
constructor() {
this.a = 1;
this.b = 'something';
}
someMethod() {
// Is this legal?
let { a, b } = this;
}
}
someMethod
中的解构赋值合法吗?
我的直觉是它很好,但我在任何文档中都没有看到这种用法的参考。它目前在 Babel 中工作,但大概是因为在幕后 Babel 正在将 class 转换为一个函数。我的理解是(几乎)JS 中的所有内容都原型继承自 Object,因此我可能希望这对于 Classes 和 Class 实例也是如此。
我所看到的关于引擎盖下发生的事情的唯一参考 is here and specifies that the JS engine calls the internal method ToObject
which will only throw a TypeError when it encounters null
or undefined
. But the ToObject
docs 没有明确提及 class 个实例。
解构对象是明确允许的,并且是一项功能。
this
仅仅指一个对象。没什么特别的。
只要 this
指的是一个对象,这绝对没问题。 *
* this
可能 而不是 引用对象,具体取决于您如何调用 someMethod
,例如Foo.someMethod.apply(null)
。但无论如何你真的有更大的问题。