在书上看到一个例子,有点错误。修改了一下。以下是我的理解!
书上是这样写的,我加了些注解:
function User(props){
    
for(var prop in props){
        (
function(currentObj){  //这里的currentObj由this传过来的。this 为 User
            alert(currentObj.constructor); //可以看出来currentObj 为User
            //创建此属性的一个新的getter(读取器)
            currentObj["get"+prop] = function(){
                
//alert(props.name+"  "+props.age+"  "+prop);
                return props[prop];
            }
            
//创建此属性的一个新的setter(设置器)
            currentObj["set"+prop] = function(val){
                props[prop] 
= val;
            };
        })(
this);  //这里的this 为 User
    }
}

var user = new User({"name":"chengkai","age":22});

//注意,name属性并不存在,因为它是属性对象(props Obj)的私有变量
alert(user.name == null); //输出 true

alert(user.getname());  
//输出 22
alert(user.getage());  //输出 22
如上:为什么会输出都为22这样呢?哈哈。这里就是闭包问题了!!

改正:
//****************动态生成方法**********************
//
props 对象,如:{"name":"chengkai","age":22}
//
************************************************
function User(props){
    for(var prop in props){
        (
function(currentObj){  //这里的currentObj由this传过来的。this 为 User
            //创建此属性的一个新的getter(读取器)
            (function(prop){
            currentObj[
"get"+prop] = function(){
                
//alert(props.name+"  "+props.age+"  "+prop);
                return props[prop];
            }
            
//创建此属性的一个新的setter(设置器)
            currentObj["set"+prop] = function(val){
                props[prop] 
= val;
            };
            })(prop);
        })(
this);  //这里的this 为 User
    }
}

var user = new User({"name":"chengkai","age":22});

//注意,name属性并不存在,因为它是属性对象(props Obj)的私有变量
alert(user.name == null); //输出 true

alert(user.getname());  
//输出 chengkai

user.setage(
11);
user.setname(
"kai");
alert(user.getage());  
//输出 11
alert(user.getname());  //输出 kai
注意前后的区别,理解了上面匿名函数的应用,应该很好看出来是么回事啦!
 posted on 2009-09-18 13:33  将军  阅读(2191)  评论(7编辑  收藏  举报