Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property initializer syntax in ESnext

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;
  }
}
like image 745
Ben Aston Avatar asked Jun 04 '17 20:06

Ben Aston


People also ask

What is a property initializer?

The new class “property initializers” allows you to define methods (or any property) in your React components using regular ES6 classes without worrying about binding.

What is Esnext syntax?

esnext is a JavaScript library for converting JavaScript written using the ES6 draft specification syntax to JavaScript that will work today.

How do you initiate an object in JavaScript?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).


1 Answers

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.

like image 198
Michał Perłakowski Avatar answered Sep 22 '22 11:09

Michał Perłakowski