我有一个现有项目(遗憾地)使用 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();
如何使下划线起作用?