Search code examples
javascriptecmascript-6destructuring

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?

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.

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. But the ToObject docs don't explicitly mention class instances.


Solution

  • Destructuring objects is explicitly allowed and is a feature.
    this merely refers to an object. There's nothing special about it.
    As long as this refers to an object, this is absolutely fine. *

    * this may not refer to an object depending on how you call someMethod, e.g. Foo.someMethod.apply(null). But then you really have bigger problems anyway.