teelou teelou - 4 months ago 16
Javascript Question

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

Answer

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');
Comments