var obj = {
Variable: 1,
Name: function() {
Variable += 1;
}
return 开发者_开发技巧this.Variable
}
var obj = {
Name: function() {
var Variable = 1;
Variable += 1;
}
return Variable
}
- Now what is the difference between these two?
- Does these two give different outputs.
1) The difference is that the definition of Variable
variable is in different location.
2) No, they have the same output: output nothing and give you error.
=== Update for your comment (Why this is invalid code?) ===
Because you cannot return
inside an object literal.
ie.
{ return "something" }
is simply incorrect.
Objects don't return. That's something functions do. You're lacking a Closure.
Your script has a lot of nonsense;
in the first case, you declare a variable "Variable" member of the object.
var obj = {
Variable: 1,
}
and you use a variable "Variable" registered in global:
var obj = {
Name: function() {
Variable += 1;
}
}
You cannot use return in your object.
var obj = {
return Variable
}
Don't know what you want...
function wrapperFunction()
{
var Obj = {
variable: 1,
....
};
return Obj ;
}
You can try also wrapping the entire object inside of a function. Then use the function to return a new instance each time the wrapping function is called.
精彩评论