最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Property initializer syntax in ESnext - Stack Overflow

programmeradmin1浏览0评论

I understand there is a TC-39 proposal for a new syntax called "property initializer syntax" in JavaScript classes.

I haven't yet found much documentation for this, but it is used in an egghead course when discussing React.

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

What is the purpose of this proposal? How does it differ from:

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

I understand there is a TC-39 proposal for a new syntax called "property initializer syntax" in JavaScript classes.

I haven't yet found much documentation for this, but it is used in an egghead course when discussing React.

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

What is the purpose of this proposal? How does it differ from:

class Foo {
  bar() {
    return this;
  }
}
Share Improve this question edited Jun 4, 2017 at 20:44 Michał Perłakowski 92.9k30 gold badges163 silver badges188 bronze badges asked Jun 4, 2017 at 20:26 Ben AstonBen Aston 55.8k69 gold badges220 silver badges349 bronze badges 2
  • Because it's a property, and not a class method, you can bind this to the function, which the arrow function does automatically. – Ori Drori Commented Jun 4, 2017 at 20:28
  • Àrrow function vs. traditional function... – le_m Commented Jun 4, 2017 at 20:28
Add a ment  | 

2 Answers 2

Reset to default 6

When you use property initializer syntax with an arrow function, this in this function will always refer to the instance of the class, whereas with regular methods, you can change this by using .call() or .bind():

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

Also, this syntax can be used for other things than functions.

From a different angle, you can use the Property initializer syntax as a shorthand for otherwise verbose method binding in constructor.

Also notice that the syntax can be used for variables as well.

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]

Property v is undefined in the allBars array where the this of unbound bar points since it was called from its context.

发布评论

评论列表(0)

  1. 暂无评论