您可以通过'this'使用速记属性分配吗?

时间:2018-11-13 21:59:46

标签: javascript ecmascript-6

我可以这样做:

class Temp {
    constructor() {
        this.foo = 'foo'
        this.bar = 'bar'
    }

    getObj() {

        let boo = 'boo'
        return {
            boo
        }
    }
}
console.log(new Temp().getObj())
//prints { boo: 'boo' }

那我该怎么做:

class Temp {
    constructor() {
        this.foo = 'foo'
        this.bar = 'bar'
    }

    getObj() {

        return {
            this.foo
        }
    }
}
console.log(new Temp().getObj())

是否有特殊语法或不支持?

4 个答案:

答案 0 :(得分:1)

我想您真正寻找的是:

return { ...this };

或者如果您想省略一些属性:

 const { bar, ...take } = this;
 return take;

答案 1 :(得分:1)

否,尚不支持此功能。您将必须经过{foo: this.foo}

但是,有一个stage 1 proposal用于简化速记属性定义,使您可以将{this.foo}编写为对象文字。

答案 2 :(得分:0)

如果要使用解构,则需要将属性提取为const,然后使用速记属性名称:

class Temp {
  constructor() {
    this.foo = 'foo'
    this.bar = 'bar'
  }

  getObj() {
    const { foo } = this;

    return {
      foo
    }
  }
}
console.log(new Temp().getObj())

答案 3 :(得分:0)

如果“ foo”是公共财产,则可以执行以下操作:

class Foo {
  constructor() {
    this.foo = 'foo';
  }
}

const { foo } = (new Foo());
console.log(foo); // 'foo'

https://repl.it/repls/FastForcefulMice

相关问题