对函数调用apply()

Calling apply() on a function

本文关键字:apply 函数调用      更新时间:2023-09-26

我有以下代码,所以当调用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"

每个函数都在上下文中执行
在js应用程序中定义的第一个对象位于全局上下文(窗口)中
在函数内部,this指的是调用上下文
平方函数没有上下文:它只取决于它的参数
有些函数需要上下文。最常见的例子是console.log。
此函数必须具有console作为上下文。如果你写:

var logMe = console.log;
logMe('hello');

你会得到:TypeError: Illegal invocation

因为console.log函数使用this===console,而当您只保留logMe=console.log===>fail的函数引用时,此上下文将丢失。

请注意,您正在使用的缓存的成本非常取决于它的实现(JSON参数),尤其是对于square()一个整数->整数函数,您最好使用一个简单的数组来缓存结果,我甚至不确定乘法是否比稀缺的数组内存访问快。我想必须进行一些基准测试,以确保缓存不会比裸计算更昂贵。