简体   繁体   中英

Javascript functions scope - best way to structure

What's the best way to structure this.. returning an object with several functions.. Fails on this.put ("this" not in scope anymore)..

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

You should change

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

to

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

The "this" variable will be overridden within the this.get ... but the myobject variable will not be.

yet another alternative is to .bind() the right this into place:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM