[英]Binding this to original object in higher-order function
在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
電話,但我想不出如何保留綁定到原來的對象。 能做到干凈嗎?
您需要在內部函數中使用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);
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.