在函数上调用apply()

时间:2014-04-27 17:18:54

标签: javascript

我有以下代码,因此在调用squareMem(10)时,this中的f.apply(this,arguments)指的是什么?

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

1 个答案:

答案 0 :(得分:1)

this将引用调用memoized函数的上下文。如果原始函数使用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"