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 ?
-
Have a look at json.org/index.htmligorshmigor– igorshmigor2018年09月13日 15:32:55 +00:00Commented Sep 13, 2018 at 15:32
2 Answers 2
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 */
}
};
Comments
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) {}
};
Comments
Explore related questions
See similar questions with these tags.