【问题标题】:How can I convert this working native ES5 code to use underscore's _.bind() instead?如何将这个工作的本机 ES5 代码转换为使用下划线的 _.bind() ?
【发布时间】:2015-10-10 14:33:48
【问题描述】:

我有一个现有项目(遗憾地)使用 underscore.js 而不是 ES5 shim 来支持 IE8 和其他非 ES5 浏览器。我习惯 ES5,但一般不使用下划线。我已经阅读了underscore documentation on _.bind 并试图让它工作。

这是一个使用原生 ES5 的工作示例

// Greets people
HelloThing = function (greeting) {
    this.greeting = greeting;

    this.waitAndSayHello = function() {
        setTimeout(function() { 
            console.log(this.greeting)
        }.bind(this), 500);
    }
}


var pretend_thing = new HelloThing('hello world');
pretend_thing.waitAndSayHello();

根据我对文档的理解,这是使用下划线的失败尝试:

// Greets people
HelloThing = function (greeting) {
    this.greeting = greeting;

    this.waitAndSayHello = function() {
        var greet = function() { 
            alert(this.greeting)
        }
        _.bind(greet, this)
        setTimeout(greet, 500);
    }
}


var pretend_thing = new HelloThing('hello world');
pretend_thing.waitAndSayHello();​

如何使下划线起作用?

【问题讨论】:

    标签: javascript underscore.js ecmascript-5


    【解决方案1】:

    _.bind() 方法返回一个绑定函数。你不会对返回的函数做任何事情。将其分配给某物并使用该引用而不是原始的 greet 引用:

    var greet = function() { 
        alert(this.greeting)
    };
    greet = _.bind(greet, this);
    setTimeout(greet, 500);
    

    如果您扩展您的 ES5 示例,您会发现这实际上是原生 bind 方法所发生的事情 - 您可以直接调用函数对象,因为它是 Function.prototype 的属性:

    var greet = function() {
        alert(this.greeting);
    };
    greet = greet.bind(this);
    setTimeout(greet, 500);
    

    【讨论】:

    • 谢谢詹姆斯,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2017-11-27
    • 1970-01-01
    • 2018-11-09
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多