What's the difference between these?
var person = {
age: 25,
name: "David"
};
var person = (function() {
var name = "David", age = 25;
}());
My question really is, what does (function(){}()) do?
What's the difference between these?
var person = {
age: 25,
name: "David"
};
var person = (function() {
var name = "David", age = 25;
}());
My question really is, what does (function(){}()) do?
What does (function(){}()) do?
This essentially creates an anonymous function and then executes it. One common use for this is limiting global variables.
For example, the following would have three global variables (var1, var2, and var3):
var var1 = "a", var2 = "b", var3 = "c";
If you wrapped these declarations in the anonymous function, they're still accessible as local variables within the anonymous function, yet do not cloud up the global namespace. For example:
(function() {
var var1 = "a", var2 = "b", var3 = "c";
console.log(var1); // interact with local variables
})(); // execute function.
What's the difference between these?
var person = {
age: 25,
name: "David"
};
If this code is contained in a function, it creates a local variable named person. Otherwise, it creates a global variable named person.
var person = (function() {
var name = "David", age = 25;
}());
This code creates and executes an anonymous function, then assigns the return code of that anonymous function to the variable person. Since the anonymous function has no return value, the variable person has a value of undefined. This statement, as it currently stands, is functionally equivalent to var person;, because the anonymous function has no side-effects and doesn't have a return value.
var person = (function() {
var name = "David", age = 25;
}());
person will be undefined, because the function doesn't have a return statement.
It is just a self executing anonymous function, you could image that as below.
function foo() {
var name = "David", age = 25;
}
var person = foo();
It executes the anonymous function you just created.
This technique is useful because it allows you to scope member in your class.
If you're looking for a good way to do classes and inheritance, take a look at http://ejohn.org/blog/simple-javascript-inheritance/
I'd also recommend defining your classes as AMD modules.