简体   繁体   English

Javascript.bind-ES5与ES6

[英]Javascript.bind - ES5 Vs ES6

How can I use bind in ES6? 如何在ES6中使用绑定?

In pre-es6 way of coding (I assume this is ES5), I would do: 在ES6之前的编码方式中(我假设这是ES5),我将这样做:

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? 但是我如何在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 . 由于访问this.respond ,因此出现错误。 But log (and respond ) is not an object method anymore, so this doesn't refer to an object with a respond method. 但是log (和respond )是不是一个对象的方法了,所以this并不是指一个物体与respond方法。 Instead you simply reference the function ( respond ) directly: 相反,您只需直接引用函数( respond ):

this.respond(...) becomes respond(...) this.respond(...)成为this.respond(...) respond(...)


However, there is no reason to use .bind at all, not even in your ES5 solution (you are never using this inside respond ). 然而,没有理由使用.bind可言,哪怕是在你ES5解决方案(你永远不会使用this内部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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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