var argument1 = {
myvar : "12",
mymethod : function(test) { return something; } // this line here
}
Is this a function statement or a function expression? And why can't I write something like this:
var argument1 = {
myvar : "12",
function f(test) { return something; }
}
but I can write this:
function func() {
myvar : "12",
function b(test) { return something; }
}
They are both objects. How can the former give error and the latter is fine?
2 Answers 2
You are defining a variable that holds an object. That object has a key
mymethodthat has a function assigned to it. It is indeed an anonymous function expression. You could do something likeargument1.mymethod('omg')This one again is a variable being assigned an object. However this object is probably not what you expect. In ES6 this will create an object with a property
functionthat has the anonymous function assigned to it. In ES5 this will fail with a syntax error. e.g.,argument1.function('yessss').This is a function declaration. When executed, the function declares a label (rare in js) named myvar then evaluates the expression
"12", tosses the result and then declares a function named b. This function will return undefined when executed. The,operator is fun and labels are funner.
Comments
Regarding your first snippet: function(x) { ... } returns an anonymous function.
Regarding your second snippet: you can do it like this:
var argument1 = {
myvar: "12",
test() { return something; }
};
Regarding your third snippet, the syntax name: expr declares a label called name, instead of an object property. (This is a common source of confusion.)
The , operator outside of a function evaluates both of its arguments and returns the second. So your third snippet labels a line myvar, then evaluates the string "12" and discards it, then declares a function.
2 Comments
var ob = {function f(){} but I can write function f(){function b(){}}. What is the difference here when ob and f are both objects? And also, the test function in your example returns anonymous function too right?var obj = function f() {};, which causes both obj and f to be defined. Or, you can not give a name, like obj = function() {};, which causes only obj to be defined. The var object = {f() { }}; is special syntax.
myvarline? Neither of the latter two examples look right to me, only the very first one. In the first example you define an object, and one of the properties on that object is a function. What are you trying to change about that and why?