Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript闭包_Javascript_Closures - Fatal编程技术网

Javascript闭包

Javascript闭包,javascript,closures,Javascript,Closures,这是一个密码 var collection = (function (){ var x = 0; return { y : x, get : function(){return x}, set : function(n) { x = n}

这是一个密码

var collection = (function (){
                var x = 0;
                return {
                    y : x,
                    get : function(){return x},
                    set : function(n) { x = n}                        
                }
              }());

collection.set(1000);

为什么
collection.y!=collection.get()。而get()将在每次调用变量x时读取该变量。

那么,设置集合的对象如下所示:

{
  y : 0,
  get : function(){return x},
  set : function(n) { x = n}                        
}

没有用于存储状态的
x
属性(编辑:为了公平起见,它将被创建,但y仍然在0值上有一个闭包,因此不会被更新),那么您还期待什么呢?将x替换为y,您应该可以。

y不是指向x的“指针”。创建闭包时,您只需将当时x的值复制到y,每次调用get()/set()时,您只对x进行操作(与y没有关系)

您是说在调用“set(1000)”之后?
function person(name,age){

    this.name=name;
    this.age=age;

    //closers
    this.sayHi=function(){

        return this.name+" say Hi"

    }

}

var p=new person("Ramesh",23);

alert(p.sayHi())