[英]In ES6 is destructuring Class Instance properties permitted?
Suppose I have the following code: 假设我有以下代码:
class Foo {
constructor() {
this.a = 1;
this.b = 'something';
}
someMethod() {
// Is this legal?
let { a, b } = this;
}
}
Is the destructuring assignment in someMethod
legal? someMethod
的解构赋值是否合法?
My gut feeling is that it is fine, but I have seen no reference to this usage in any docs. 我的直觉是它很好,但我在任何文档中都没有看到过这种用法。 It currently works in Babel, but presumably because under the hood Babel is transpiling the class into a function.
它目前在巴贝尔工作,但可能是因为在引擎盖下巴贝尔正在将课程转化为一个功能。 My understanding is that (almost) everything in JS prototypically inherits from Object, so I might expect this to be true for Classes and Class instances too.
我的理解是(几乎)JS中的所有内容都是原型继承自Object,所以我可能期望这对Classes和Class实例也是如此。
The only reference I've seen to what happens under the hood 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
. 我所看到的唯一引用是在引擎盖下发生的事情,并指定JS引擎调用内部方法
ToObject
,它只会在遇到null
或undefined
时抛出TypeError。 But the ToObject
docs don't explicitly mention class instances. 但是
ToObject
文档没有明确提到类实例。
Destructuring objects is explicitly allowed and is a feature. 明确允许解构对象,这是一个功能。
this
merely refers to an object. this
只是指一个物体。 There's nothing special about it. 没什么特别的。
As long as this
refers to an object, this is absolutely fine. 只要
this
指的是一个物体,这绝对没问题。 * *
* this
may not refer to an object depending on how you call someMethod
, eg Foo.someMethod.apply(null)
. *
this
可能不会引用一个对象,具体取决于你如何调用someMethod
,例如Foo.someMethod.apply(null)
。 But then you really have bigger problems anyway. 但无论如何你真的有更大的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.