gpt4 book ai didi

javascript - 在函数上调用 apply()

转载 作者:行者123 更新时间:2023-12-03 12:46:33 25 4
gpt4 key购买 nike

我有以下代码,那么当调用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com