2

I've seen some people use

created: function() {
  // code
}

and also

created () {
  // code
}

and then a warning in the Vue docs to not do this

created: () => {
  // code
} 

I understand that the first one is the usual way of writing functions, and the last one is the new es6 arrow functions which bind the 'this' keyword to scope. But what is the middle one? It looks like a mix of both. What're the implications of using that?

Kelvin Zhao
  • 2,243
  • 3
  • 22
  • 31
  • 1
    Middle one is probably from a javascript class https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – charlietfl Dec 10 '17 at 07:19
  • Are you sure there's not a `function` before the second one, as in `function created () { // code }`? As written, it's invalid syntax unless it's in a class (h/t @charlietfl, who pointed this out first). – elixenide Dec 10 '17 at 07:20
  • 1
    @EdCottrell It's also valid in an object literal (like the first and third examples would be) – Bergi Dec 10 '17 at 11:51

1 Answers1

1

The first and the second are identical. The second one just is a ES6 syntax to defining function in the object.

const obj1 = {
  name: 'Obj1',
  create() {
    console.log(this.name);
  }
};

const obj2 = {
  name: 'Obj2',
  create: function() {
    console.log(this.name);
  }
};

obj1.create();
obj2.create();
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112