简体   繁体   中英

Javascript.bind - ES5 Vs ES6

How can I use bind in ES6?

In pre-es6 way of coding (I assume this is ES5), I would do:

var app = {};
app.log = function(req, res) {
    var respond = this.respond.bind(this, req, res);
    return respond(400, 'no data received');
}

app.respond = function(req, res, status, message) {
    console.log(req); // hello
    console.log(status); // 400
    console.log(message); // no data received
}

app.log('hello');

But how I can do that in ES6?

export default function log (req, res) {
    var respond = this.respond.bind(this, req, res);
    return respond(400, 'no data received');
}

function respond (req, res, status, message) {
    console.log(req); 
    console.log(status); 
    console.log(message); 
}

Of course I will get an error:

TypeError: Cannot read property 'respond' of undefined

You are getting the error because you are accessing this.respond . But log (and respond ) is not an object method anymore, so this doesn't refer to an object with a respond method. Instead you simply reference the function ( respond ) directly:

this.respond(...) becomes respond(...)


However, there is no reason to use .bind at all, not even in your ES5 solution (you are never using this inside respond ).

All you have to do is call the function:

export default function log (req, res) {
  return respond(req, res, 400, 'no data received');
}

I don't think you have to use export in this case. Simply make a class.

class App {

    log(req, res) {
        var respond = this.respond.bind(this , req , res);
        return respond(400, 'no data received');
    }

    respond(req, res, status, message) {
        console.log(req);
        console.log(status);
        console.log(message);
    }

}

var app = new App();
app.log('hello');

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