There are ready-made shortcuts (syntactic sugar) to the function wrapper @CMS answered with. (Below assuming that the context you want is this.tip
.)
For virtually all javascript development (in 2020) you can use fat arrow functions, which are part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification.
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this
value [...].
(param1, param2, ...rest) => { statements }
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy(); }, 1000);
}
If you target browser compatible with ECMA-262, 5th edition (ECMAScript 5) or Node.js, which (in 2020) means all common browsers as well as older browsers, you could use Function.prototype.bind
. You can optionally pass any function arguments to create partial functions.
fun.bind(thisArg[, arg1[, arg2[, ...]]])
Again, in your case, try this:
if (this.options.destroyOnHide) {
setTimeout(this.tip.destroy.bind(this.tip), 1000);
}
The same functionality has also been implemented in Prototype (any other libraries?).
Function.prototype.bind
can be implemented like this if you want custom backwards compatibility (but please observe the notes).
If you are already using jQuery 1.4+, there's a ready-made function for explicitly setting the this
context of a function.
jQuery.proxy(): Takes a function and returns a new one that will always have a particular context.
$.proxy(function, context[, additionalArguments])
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}
It's available in Underscore.js, as well as lodash, as _.bind(...)
1,2
bind Bind a function to an object, meaning that whenever the function is called, the value of this
will be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application.
_.bind(function, object, [*arguments])
In your case, try this:
if (this.options.destroyOnHide) {
setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}
bind jquery underscore.js ecmascript-5 prototypejs node.js