1

I have the following question : in Node/Javascript why this function declaration is wrong inside an object or a class??

var obj = {
 function x() {
 /* code */
 },
 bar: function() {
 /* code */
 }
};

the first function declaration x() cause

 function x() {
 ^
SyntaxError: Unexpected identifier

i don't understand why i can't use the function keyword inside an object or a class , what difference does it make when using function x() or just x(), just x() works fine , but adding function keyword in front of it - cause the above problem. why ?

cнŝdk
32.2k7 gold badges62 silver badges81 bronze badges
asked Sep 13, 2018 at 15:30
1

2 Answers 2

3

You need to assign a key in Javascript to their objects, the second one works because you have a key assigned to it that is bar, in the first one not. Try adding the key before the function declaration,like this:

var obj = {
 foo:function x() {
 /* code */
 },
 bar: function() {
 /* code */
 }
};
answered Sep 13, 2018 at 15:37
Sign up to request clarification or add additional context in comments.

Comments

2

in Node/Javascript why this function declaration is wrong inside an object or a class??

Of course it's wrong, in JavaScript an object is pairs of key/values, separated with comma. With your code, you are breaking this syntax, because you are not declaring a property in your case, you need to specify the key before writing function x().

If you refer to MDN Object initializer reference you can see that:

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 ({}).

And if you check the New notations in ECMAScript 2015 section of Docs you will see the difference between writing function x(), x() or just x().

And according to the docs these are possible Method definitions syntaxes:

var o = {
 property: function (parameters) {},
 get property() {},
 set property(value) {}
};
answered Sep 13, 2018 at 15:32

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.