简体   繁体   English

将此对象绑定到高阶函数中的原始对象

[英]Binding this to original object in higher-order function

In JavaScript, is it possible to bind the this object to a function returned by a higher-order function? 在JavaScript中,可以this对象绑定到由高阶函数返回的函数吗? 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. 在此示例中, restrict()函数正确地传递给它正在包装的函数,但未在myObj函数的上下文中执行。 I have tried various this bindings in the apply call, but I cannot figure out how to retain the binding to the original object. 我曾尝试过各种this绑定在apply电话,但我想不出如何保留绑定到原来的对象。 Can this be done cleanly? 能做到干净吗?

You need to use this within your inner function: 您需要在内部函数中使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM