In JavaScript, is it possible to bind the this
object to a function returned by a higher-order function? The code sample below is essentially what I am using:
var restrict = function(restrictOn, fn) {
var that = this;
return function() {
if (arguments[0] === restrictOn) {
throw new Error("Condition not met");
}
return fn.apply(/*original object*/that, arguments);
};
};
var MyConstr = function(name) {
this.name = name;
};
MyConstr.prototype.sayNameWhenNotThree = restrict(3, function() {
return this.name;
});
var myObj = new MyConstr("Fido");
myObj.sayNameWhenNotThree(3); // Throws error - OK
myObj.sayNameWhenNotThree(5); // SHOULD return "Fido" - does not
In this example, the restrict()
function correctly passes through to the function that it is wrapping, but it is not executing in the context of the myObj
function. I have tried various this
bindings in the apply
call, but I cannot figure out how to retain the binding to the original object. Can this be done cleanly?
You need to use this
within your inner function:
var restrict = function(restrictOn, fn) {
/* at this point this refers to whatever context restrict
is called in, in this case - it's window */
return function() {
if (arguments[0] === restrictOn) {
throw new Error("Condition not met");
}
/* at this point this refers to the proper target that the returned
function is being assigned to */
return fn.apply(this, arguments);
};
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.