@CMS 回答的函数包装器有现成的快捷方式(语法糖)。 (下面假设你想要的上下文是this.tip。)
对于几乎所有的 javascript 开发(2020 年),您都可以使用 胖箭头函数,它们是 part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification。
arrow function expression(也称为胖箭头函数)与函数表达式相比语法更短,并且在词法上绑定了this 值[...]。
(param1, param2, ...rest) => { statements }
在你的情况下,试试这个:
if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy(); }, 1000);
}
如果您定位到browser compatible with ECMA-262, 5th edition (ECMAScript 5) 或Node.js(2020 年)意味着所有常见的浏览器以及旧版浏览器,您可以使用Function.prototype.bind。您可以选择传递任何函数参数来创建partial functions。
fun.bind(thisArg[, arg1[, arg2[, ...]]])
同样,在你的情况下,试试这个:
if (this.options.destroyOnHide) {
setTimeout(this.tip.destroy.bind(this.tip), 1000);
}
implemented in Prototype(任何其他库?)也具有相同的功能。
Function.prototype.bind can be implemented like this 如果您想要自定义向后兼容性(但请注意注释)。
如果您已经在使用 jQuery 1.4+,有一个现成的函数可以显式设置函数的 this 上下文。
jQuery.proxy():接受一个函数并返回一个始终具有特定上下文的新函数。
$.proxy(function, context[, additionalArguments])
在你的情况下,试试这个:
if (this.options.destroyOnHide) {
setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}
它在 Underscore.js 和 lodash 中可用,如 _.bind(...)1,2
bind 将函数绑定到对象,这意味着每当调用该函数时,this 的值将是该对象。或者,将参数绑定到函数以预先填充它们,也称为部分应用。
_.bind(function, object, [*arguments])
在你的情况下,试试这个:
if (this.options.destroyOnHide) {
setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}
bindjqueryunderscore.jsecmascript-5prototypejsnode.js