简体   繁体   中英

Defining methods/functions on Javascript Objects

Is this:

saveUpdate() {
   // Some code
}

The same as:

saveUpdate: function() {
   // Some code
}

Is there a best practice (ES6) way to define methods on objects (specifically, Vue.js components)?

More context: I am having trouble in my Vue.js application with the methods triggering properly in productions. The methods I have defined seem to work fine in development - but once compiled for production they do not seem to behave in the same way. I have read in the Vue.js documentation that all methods need to be defined as NEW separate functions, and I am now wondering if the way I am defining the methods; is actually not correct.

broader example:

...,
methods: {
  saveUpdate() {
   // Some code
  }
},
...

should I be doing something like:

...,
methods: {
  saveUpdate: () => {
   // Some code
  }
},
...

What is the modern, best practice or accepted way to do this? Or am I looking in the wrong place and my declarations are just fine the way they are?

Yes, this:

saveUpdate() {
   // Some code
}

Is syntactic sugar for:

saveUpdate: function() {
   // Some code
}

There's nothing different between the two bar the syntax. If you want an arrow function, I believe you need to use the second form:

saveUpdate: () => {
   // Some code in a lexical `this` scope (not useful in Vue computed).
}

Also note that the -> syntax is invalid - it's a fat arrow => . Although as Phil pointed out in the comments, you most likely won't want to use arrow functions in a Vue project as you'd lose the binding to this which is how you interact with your component.

saveUpdate() {...} is ES6 shortcut for saveUpdate: function() {...} , so yes they are the same. Since Vue applications are commonly transpiled, there is no reason to not use the first option.

If a function is reused within application, it can be declared separately:

export function saveUpdate() {...}

...

export default {
  methods: { saveUpdate }
}

Arrows shouldn't be used for functions that expect to access Vue instance as this .

As the documentation explains:

All lifecycle hooks are called with their this context pointing to the Vue instance invoking it.

Don't use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()) . Since an arrow function doesn't have a this, this will be treated as any other variable and lexically looked up through parent scopes until found, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM