在高阶函数中将其绑定到原始对象

时间:2014-11-11 15:28:20

标签: javascript this

在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绑定,但我无法弄清楚如何保留对原始对象的绑定。这可以干净利落吗?

1 个答案:

答案 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);
   };
};