2

我有一个现有项目(遗憾地)使用 underscore.js 而不是 ES5 shim 来支持 IE8 和其他非 ES5 浏览器。我习惯 ES5,但一般不使用下划线。我已阅读_.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();​

如何使下划线起作用?

4

1 回答 1

3

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

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

If you expand your ES5 example, you will see that this is effectively what is happening with the native bind method - you can just call directly on a function object since it's a property of Function.prototype:

var greet = function() {
    alert(this.greeting);
};
greet = greet.bind(this);
setTimeout(greet, 500);
于 2012-10-30T09:58:05.240 回答