JavaScript闭包

8

这是一段代码

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()

你的意思是在调用“set(1000)”之后吗? - Aziz
5个回答

8

y不是指向x"指针"。创建闭包时,您只是将x在那个时刻的值复制到了y中,每次调用get()/set()时,您只操作x(与y无关)。


4

当你调用collection.set(1000)时,你没有设置集合y。

该语句涉及IT技术。

3

好的,你要设置集合的对象看起来像这样:

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

没有x属性来存储状态(编辑:公平地说,它将被创建,但是y仍然对0值具有闭包,因此不会更新),那么你还期望什么呢?用y替换x,你就可以了。


3
因为 y 将会存储数值 0,并且不会从 x 中读取。而 get() 会在每次调用时都读取变量 x

0
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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接