Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将其绑定到高阶函数中的原始对象_Javascript_This - Fatal编程技术网

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

在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
函数的上下文中执行。我在
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)中使用?我相信在这一点上,它应该是指正确的对象?哈!我想这是我唯一没有尝试过的想法,但它奏效了!如果你把它作为答案写下来,我会接受的。