what means return { someObject : someObject }
I saw this code, after looking for a while and look for on the internet I still do not get it.
var client = function (){
var engine = {
ie: 0,
gecko: 0,
webkit: 0,
version: null
};
return {
engine : engine
};
}();
My specific question is about the return statement. I know that:
client
开发者_C百科is a function that var engine = { ... }
is creating a object engine with some properties inside and a default values, but I do not understand the return
and why at the of the function it has ()
.
This expression the variable client
is being assigned to is both
- Defining a function which returns an object expression
- Invoking that function and using the result as the new value for
client
A more long winded way of writing that code is
var method = function(){
var engine = {
ie: 0,
gecko: 0,
webkit: 0,
version: null
};
return {
engine : engine
};
};
var client = method();
The inner function is returning an associative array (a dictionary, if you will) where the key engine
maps to the engine
variable. The "engine" before the colon is the dictionary key and is treated as text rather than a variable. It might be clearer to look at it as
return {
"engine" : engine
};
which works identically.
So, after this code runs, you can access client.engine
and that will get you the "engine" that was built in the internal function.
It creates an object client
that looks like this:
Object
engine: Object
gecko: 0
ie: 0
version: null
webkit: 0
I think it's written to illustrate some points about JavaScript, because it could be simpler written:
var client = {
engine: {
ie: 0,
gecko: 0,
webkit: 0,
version: null
}
};
精彩评论