在JavaScript中,是否可以将this
对象绑定到高阶函数返回的函数?下面的代码示例基本上就是我正在使用的代码:
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
在此示例中,restrict()
函数正确地传递给它正在包装的函数,但它不在myObj
函数的上下文中执行。我在this
调用中尝试了各种apply
绑定,但我无法弄清楚如何保留对原始对象的绑定。这可以干净利落吗?
答案 0 :(得分:2)
您需要在内部函数中使用this
:
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);
};
};