我有以下代码,那么当调用squareMem(10)
时,f.apply(this,arguments)
中的this
是做什么的指的是?
function square(num){
return num*num;
}
function memoize(f){
var cache = {};
return function(){
var key = JSON.stringify(Array.prototype.slice.call(arguments));
if(key in cache){
console.log('From cache...');
return cache[key];
}else{
console.log('Computing..');
return cache[key] = f.apply(this,arguments); // what does `this` refer to?
}
}
}
var squareMem = memoize(square);
squareMem(10);//100
最佳答案
this
将引用调用内存函数的上下文。仅当原始函数使用 this
时,它才真正有用:
function square2(num) {
return this + ": " + (num*num);
}
var o = { };
var d = new Date();
var f = memoize(square2);
o.f = memoize(square2);
d.f = memoize(square2);
f(20) => "[object Window]: 400"
o.f(20) => "[object Object]: 400"
d.f(20) => "Sun Apr 27 2014 15:03:41 GMT-0500 (CDT): 400"
关于javascript - 在函数上调用 apply(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23326491/