JavaScript(三)笔记call、apply与bind
call与apply基本相同,它们都是为了实现绑定对应的上下文,不同在于call是对应参数列表,apply可以是数组。
call.(上下文,参数)
bind也是相同的操作,不同在于只执行绑定与改变上下文,并未实际执行函数。
综合应用1 缓冲,避免多次计算
let show = {
name: "abc",
slow: function (value1, value2) {
alert(`first test ,${this.name}`);
return value1 + value2;
}
};
function Cathrepeat(func, hash) {
let map = new Map();
return function (...args) {
let key = hash(args);
// alert(`args = ${args},key = ${key}`);
if (map.has(key)) {
return map.get(key);
}
//三种用法
let result = func.bind(this, ...args)();
//let result = func.call(this,...args);
//let result = func.apply(this,args);
map.set(key, result);
return result;
};
}
function hash(...args) {
return args.join();
}
show.slow = Cathrepeat(show.slow, hash);
alert(show.slow(4, 5));
alert(show.slow(4, 5));
alert(show.slow(5, 7));