Javascript 将其绑定到高阶函数中的原始对象
在JavaScript中,是否可以将Javascript 将其绑定到高阶函数中的原始对象,javascript,this,Javascript,This,在JavaScript中,是否可以将this对象绑定到高阶函数返回的函数?下面的代码示例基本上就是我正在使用的: var restrict = function(restrictOn, fn) { var that = this; return function() { if (arguments[0] === restrictOn) { throw new Error("Condition not met"); } retu
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
函数的上下文中执行。我在apply
调用中尝试了各种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);
};
};
您是否尝试过在返回的函数中使用
this
,即直接在fn.apply(this,arguments)中使用代码>?我相信在这一点上,它应该是指正确的对象?哈!我想这是我唯一没有尝试过的想法,但它奏效了!如果你把它作为答案写下来,我会接受的。