【问题标题】:Property initializer syntax in ESnextESnext 中的属性初始化器语法
【发布时间】:2017-11-05 14:35:49
【问题描述】:

据我所知,有一个 TC-39 提议,在 JavaScript classes 中提出了一种称为“属性初始化器语法”的新语法。

我还没有找到太多这方面的文档,但是在讨论 React 时,它被用在了一个蛋头课程中。

class Foo {
  bar = () => {
    return this;
  }
}

这个提议的目的是什么?与以下有何不同:

class Foo {
  bar() {
    return this;
  }
}

【问题讨论】:

  • 因为它是一个属性,而不是一个类方法,你可以将this绑定到函数,箭头函数会自动完成。
  • 箭头函数与传统函数...

标签: javascript ecmascript-next


【解决方案1】:

从另一个角度,您可以使用属性初始化器语法作为构造函数中其他冗长方法绑定的简写。

还要注意语法也可以用于变量。

class Property {
  v = 42

  bar = () => {
    return this.v
  }
}
// --------

class Bound {
  constructor() {
    this.v = 43
    this.bar = this.bar.bind(this)
  }

  bar() {
    return this.v;
  }
}
// --------

class Classic {
  constructor() {
    this.v = 44
  }

  bar() {
    return this.v;
  }
}

,

const allBars = [
  new Property().bar,
  new Bound().bar,
  new Classic().bar
]

console.log([
  allBars[0](),
  allBars[1](),
  allBars[2]()
])

// prints: [42, 43, undefined]

属性 v 在 allBars 数组中未定义,其中未绑定的 barthis 指向它,因为它是从其上下文中调用的。

【讨论】:

    【解决方案2】:

    当您将属性初始化语法与箭头函数一起使用时,此函数中的this 将始终引用类的实例,而对于常规方法,您可以使用.call().bind() 更改this

    class Foo {
      constructor() {
        this.test = true;
      }
      bar = () => {
        return this;
      }
    }
    console.log(new Foo().bar.call({}).test); // true
    
    class Foo2 {
      constructor() {
        this.test = true;
      }
      bar() {
        return this;
      }
    }
    console.log(new Foo2().bar.call({}).test); // undefined

    此外,此语法还可用于函数以外的其他事物。

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 2020-03-05
      • 2016-06-17
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      相关资源
      最近更新 更多