简体   繁体   English

ES6 在类中使用 this 进行解构

[英]ES6 Destructuring with this inside a class

I have a function that returns a tuple [number, number, number] .我有一个返回元组[number, number, number]的函数。 I want to use destructuring to assign to my class variables the values returned by the tuple like this:我想使用解构将元组返回的值分配给我的类变量,如下所示:

let [this.a, this.b, this.c] = functionThatReturnsTupleWithThreeNumbers()

but this doesn't work.但这不起作用。

Just remove the let and you're good to go:只需删除let就可以了:

 class Foo { a; b; c; bar() { [this.a, this.b, this.c] = [1, 2, 3]; } } const foo = new Foo(); foo.bar(); console.log(foo);

More info here更多信息在这里

Typescript playground打字稿游乐场

You need to have the props in your class and destruct your tuple into them:您需要在您的班级中拥有道具并将您的元组分解为它们:

class MyClass {
    a: number;
    b: number;
    c: number;

    constructor(tuple: ReadonlyArray<number>) {
        [this.a, this.b, this.c] = tuple;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM