开发者

Variable Scope in JavaScript

开发者 https://www.devze.com 2023-03-20 04:12 出处:网络
var obj = { Variable: 1, Name: function() { Variable+= 1; } return 开发者_开发技巧this.Variable } var obj = {
var obj = {

    Variable: 1, 

    Name: function() {
      Variable  += 1;
    }

   return 开发者_开发技巧this.Variable
}

var obj = {

    Name: function() {
      var Variable = 1;
      Variable  += 1;
    }

   return Variable
}
  1. Now what is the difference between these two?
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消