【问题标题】:What is 'this' in this use of apply within this js implementation of memoize?在 memoize 的这个 js 实现中使用 apply 中的“this”是什么?
【发布时间】:2016-06-29 16:32:04
【问题描述】:
_.memoize = function(func) {
  var cache = []; 
  return function(n){
    if(cache[n]){
        return cache[n];
    }
    cache[n] = func.apply(this,arguments);
    return cache[n];
  }
};

我只是想了解为什么在 func.apply 中使用“this”...它指的是什么?

【问题讨论】:

标签: javascript this apply


【解决方案1】:

如果使用相同的第一个参数(例如 1)进行了函数调用,则您的函数 memoize 返回一个缓存结果的新函数。

function#apply 接受两个参数:

  1. 当前上下文(在您的函数中也称为 this
  2. 您要传入的参数数组(类似)。

this 只是指调用你的函数的上下文。将它传递给apply 只是确保你的记忆函数继续像普通 JS 函数所期望的那样工作。

几个例子:

var a = function(number) {
    console.log(this);
}

var b = _.memoize(a);

a(1); // this refers to window
b(1); // this refers to window as well

a.call({ test: true }); // this refers to { test: true }
b.call({ test: true }); // this refers to { test: true } as well

例如,如果您要传递 null 而不是 this 作为 func.apply 的第一个参数...

cache[n] = func.apply(null, arguments);

……它不再起作用了:

a(1); // this refers to window
b(1); // this refers to window as well

a.call({ test: true }); // this refers to { test: true }
b.call({ test: true }); // this refers to window

strict mode 中,this 对于b 将始终为null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2014-08-20
    • 2011-07-18
    • 2016-04-13
    • 1970-01-01
    • 2017-04-25
    相关资源
    最近更新 更多