1

What is the difference between method1 and method2 ?

let myObject = {
 method1: function(x){
 console.log(...);
 },
 method2(x){
 console.log(...);
 }
}
asked Sep 25, 2017 at 9:32
7
  • 4
    @Glubus, Jamiec: it IS valid es2015 (if we add that comma): monosnap.com/file/tpWRqrOSNB2q4sjwm7HbVCLWOX7sCU.png Commented Sep 25, 2017 at 9:37
  • 6
    Semantically, these methods are equivalent, and contrary to the claims above, this is valid JavaScript ES6 except for the missing comma between the two function bodies within the object literal. Commented Sep 25, 2017 at 9:38
  • 1
    To help better understand your need for asking - why do you think there is a difference? Commented Sep 25, 2017 at 9:41
  • 1
    @JamesThorpe just needed to know if there can be a difference in any way like binding or scope or anything else Commented Sep 25, 2017 at 9:42
  • 1
    @YouMa there is no difference in binding or scope. Object literal member methods are just like regular ES5 syntax functions assigned to object keys, as in method1. Commented Sep 25, 2017 at 9:45

2 Answers 2

2

There is no difference. method2 is just a shorthand syntax introduced in ES6.

Starting with ECMAScript 2015, a shorter syntax for method definitions on objects initializers is introduced. It is a shorthand for a function assigned to the method's name.

Source: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Method_definitions

Suraj Rao
29.7k11 gold badges96 silver badges104 bronze badges
answered Sep 25, 2017 at 9:45
Sign up to request clarification or add additional context in comments.

Comments

1

There is no real difference here, as stated in the comments.

It's just a matter of "how do you want to write it".

But if you're starting a project, you should choose one way and stick to it, and if the project is already started, try to stick to the way the most used. It'll greatly help to read the code easily.

Also, if it's about scope or binding, you should have a look here :

http://2ality.com/2015/02/es6-scoping.html

answered Sep 25, 2017 at 9:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.