2 回答
TA贡献1830条经验 获得超3个赞
编辑:总之,早在2010年这个问题被问到的时候,解决这个问题最常见的方法就是保存对setTimeout函数调用,因为setTimeout使用this指向全局对象:
var that = this;if (this.options.destroyOnHide) {
setTimeout(function(){that.tip.destroy()}, 1000);}在ES5规范中,刚刚发布了一年前,它引入了bind方法在最初的答案中并没有提到这一点,因为它还没有得到广泛的支持,而且您需要使用多填充技术,但是现在它无处不在了:
if (this.options.destroyOnHide) {
setTimeout(function(){ that.tip.destroy() }.bind(this), 1000);}这个bind函数创建一个新函数。this值预填充。
在现代JS中,这正是箭头函数解决的问题。ES6:
if (this.options.destroyOnHide) {
setTimeout(() => { that.tip.destroy() }, 1000);}箭头函数没有this值,当您访问它时,您将访问this包围词法范围的值。
HTML 5也标准化定时器回到2011年,您可以将现在的参数传递给回调函数:
if (this.options.destroyOnHide) {
setTimeout(function(that){that.tip.destroy()}, 1000, this);}TA贡献1770条经验 获得超3个赞
this.tip.)
ECMAScript 5 (当前浏览器 、Node.js)和Prototype.js
Function.prototype.bind
fun.bind(thisArg[, arg1[, arg2[, ...]]])
if (this.options.destroyOnHide) {
setTimeout(this.tip.destroy.bind(this.tip), 1000);}Function.prototype.bind
ECMAScript 2015 (一些浏览器 、Node.js 5.0.0+)
阿 箭头函数表达式(亦称 脂肪箭头功能)具有比函数表达式更短的语法,并且在词汇上绑定 this价值[.]
(param1, param2, ...rest) => { statements }if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy(); }, 1000);}jQuery
this
jQuery.Proxy() *获取一个函数并返回一个始终具有特定上下文的新函数。
$.proxy(function, context[, additionalArguments])
if (this.options.destroyOnHide) {
setTimeout($.proxy(this.tip.destroy, this.tip), 1000);}Underscore.js , 房客
_.bind(...)1,2
绑定
将函数绑定到对象,这意味着每当调用该函数时, this将成为目标。或者,将参数绑定到函数以预先填充它们,也称为部分应用程序。
_.bind(function, object, [*arguments])
if (this.options.destroyOnHide) {
setTimeout(_.bind(this.tip.destroy, this.tip), 1000);}添加回答
举报
