0

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

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);
            })
    }
4

2 回答 2

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 变量不会。

于 2013-06-18T03:21:24.520 回答
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) );
    }
}
于 2013-06-18T04:05:36.303 回答