我有一个现有项目,该项目(可悲的是)使用underscore.js而不是ES5垫片来支持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();
如何使下划线工作?
_.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);