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?

3
  • 1
    Middle one is probably from a javascript class developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Dec 10, 2017 at 7: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). Commented Dec 10, 2017 at 7:20
  • 1
    @EdCottrell It's also valid in an object literal (like the first and third examples would be) Commented Dec 10, 2017 at 11:51

1 Answer 1

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();

Sign up to request clarification or add additional context in comments.

4 Comments

that isn't es5 compatible
yes... to be honest i knew you could do that in new classes...didn't know it worked in object literals too
@charlietfl ES6 introduces a couple of useless syntactic sugars indeed (in my humble opinion).
@WaldemarIce I know this is hard to admit, but ES6 was not necessary :-P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.