Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

ES5 set如何设置值?

代码是这样的

function(){
        window.Observer = function(data){
            this.data=data;
            for(var key in this.data){
                var val = this.data[key]; ---这里
                this.walk(val,key);       
            }
        };
        Observer.prototype.walk = function(val,key){
            Object.defineProperty(this.data,key,{
                enumerable: true,
                configurable: true,
                get:function(){
                    return val;
                },
                set:function(newValue){
                    val = newValue; --- 这里
                }
            })
        };
    })()
 
 
var app = new Observer({a:"a"});
 
console.info(app.data.a);
         
app.data.a = "b"; 
 
console.info(app.data.a);

然后输出为 a b;

为什么通过val = newValue可以设置a属性的值?
val难道是一个引用?

如果val存的是地址,可是这样为什么又不行

var a = {b:0}
var val = a.b;
val = 1
 
//a.b仍然是0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

找到答案了,,, val不是引用,就是值 ,之所以通过val = newValue可以设置app.data.a的值,是因为这是个闭包,里面保存了val的值,所以获得app.data.a的值时,调用get方法,返回的也是val.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...