Javascript函数范围 - 结构的最佳方式

时间:2013-06-18 03:18:16

标签: javascript scope

结构化的最佳方法是什么..返回具有多个函数的对象.. 在this.put上失败(“这个”不再在范围内了)..

return {
    put: function(o, cb){
        fs.writeFile(fn, JSON.stringify(o, null, 4), function(e, r){
                if(e) throw e;
                cb(o);
            })      
        },
    setItem: function(n, v, cb){
            this.get(function(o){
                o[n] = v;
                this.put(o, cb);
            })
    }

2 个答案:

答案 0 :(得分:1)

你应该改变

setItem: function(n, v, cb){
        this.get(function(o){
            o[n] = v;
            this.put(o, cb);
        })
}

setItem: function(n, v, cb){
        var myobject = this;
        this.get(function(o){
            o[n] = v;
            myobject.put(o, cb);
        })
}

“this”变量将在this.get中被覆盖...但myobject变量不会被覆盖。

答案 1 :(得分:0)

另一个替代方法是.bind()正确这个到位:

return {
    put: function(o, cb){
        fs.writeFile(fn, JSON.stringify(o, null, 4), function(e, r){
                if(e) throw e;
                cb(o);
            })      
        },
    setItem: function(n, v, cb){
            this.get(function(o){
                o[n] = v;
                this.put(o, cb);
            } .bind(this) );
    }
}