javascript - 在 Javascript apply 中使用 'this' 作为函数

标签 javascript functional-programming

    Function.prototype.defer = function(ms) {
    let f = this
    return function(...args) {
        setTimeout(()=>this.apply(this, args), ms); //**
    }
};


function f(a, b) {
  alert( a + b );
}

f.defer(1000)(1, 2); // shows 3 after 1 second

所以上面的代码给出了一个错误,说“this.apply不是一个函数”。但是,如果我将 (**) 行更改为

setTimeout(()=>f.apply(this, args), ms);

即使 f 仍然引用“this”,代码也运行良好。是什么赋予了?

最佳答案

让我们看一下问题中提供的代码,以了解其工作原理以及 另一个没有。

让我们首先看一下功能示例:

Function.prototype.defer = function (ms) {
  let f = this;
  return function(...args) {
    setTimeout(() => f.apply(this, args), ms);
  };
};

function f(a, b) {
  alert(a + b);
}

f.defer(1000)(1, 2); // shows 3 after 1 second
// translates to
setTimeout(() => f.appy(this, [1, 2]), 1000);
//                       ^
// here `this` refers to the global object (window)

让我们看一下不起作用的示例:

Function.prototype.defer = function (ms) {
  return function(...args) {
    setTimeout(() => this.apply(this, args), ms);
  };
};

function f(a, b) {
  alert(a + b);
}

f.defer(1000)(1, 2); // shows 3 after 1 second
// translates to
setTimeout(() => this.appy(this, [1, 2]), 1000);
//                ^         ^
// here `this` refers to the global object (window)

由于上述上下文中的 this 指向全局对象(窗口),您可以 也可以写成:

setTimeout(() => window.appy(window, [1, 2]), 1000);

由于 window 是一个对象而不是函数,这解释了您所遇到的错误 得到。

关于javascript - 在 Javascript apply 中使用 'this' 作为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195400/

相关文章:

javascript - 如何在调用另一个方法后调用js对象的方法?

javascript - Velocity js 翻译问题

haskell - 为什么 Haskell 中的联积类型没有简单的语法?

loops - 迭代向量的相邻元素时如何避免循环

javascript - Jquery 将选项标签设置为选中

javascript - 无法从维基百科 API 获取数据

parsing - 语言设计 : How does evaluation of parsed expressions work in Haskell?

multithreading - 函数式编程中不可变数据的问题

javascript - 递归使用 Javascript 返回未定义

javascript - Kendo图表数据标签格式