Javascript 如何将此正常工作的本机ES5代码转换为使用下划线';是否改为使用s\ux.bind()?

Javascript 如何将此正常工作的本机ES5代码转换为使用下划线';是否改为使用s\ux.bind()?,javascript,underscore.js,ecmascript-5,Javascript,Underscore.js,Ecmascript 5,我有一个现有的项目(遗憾的是)使用下划线.js而不是ES5垫片来支持IE8和其他非ES5浏览器。我习惯于ES5,但一般不使用下划线。我已经阅读了这篇文章,并试图让它发挥作用 下面是一个使用本机ES5的工作示例: // Greets people HelloThing = function (greeting) { this.greeting = greeting; this.waitAndSayHello = function() { setTimeout(fu

我有一个现有的项目(遗憾的是)使用下划线.js而不是ES5垫片来支持IE8和其他非ES5浏览器。我习惯于ES5,但一般不使用下划线。我已经阅读了这篇文章,并试图让它发挥作用

下面是一个使用本机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();​
如何使下划线起作用?

该方法返回绑定函数。您不需要对返回的函数执行任何操作。将其分配给某个对象并使用该引用,而不是原始的
greet
引用:

var greet = function() { 
    alert(this.greeting)
};
greet = _.bind(greet, this);
setTimeout(greet, 500);
如果您扩展ES5示例,您将看到本机的
bind
方法实际上就是这样-您可以直接调用函数对象,因为它是
函数的属性。prototype

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

谢谢,詹姆斯,非常感谢。