虚拟代理
Lucy不用关心儿子怎么通知Jack去拿快递的,让儿子自己把要干啥跟dad说就好了。
// 虚拟代理
var lucy = {
receive: function () {
son.sayToDad();
}
}
var jack = {
take: function (what) {
console.log("take ", what);
}
}
var son = {
sayToDad: function () {
var express = "kuai di";
jack.take(express);
}
}
lucy.receive();
缓存代理
// 缓存代理
var mult = function () {
var result = 1;
var length = arguments.length;
for (var i = 0; i < length; i++) {
result *= arguments[i];
}
return result;
}
var plus = function () {
var result = 0;
var length = arguments.length;
for (var i = 0; i < length; i++) {
result += arguments[i];
}
return result;
}
var computeProxy = function (fn) {
var cache = {};
return function () {
var id = Array.prototype.join.call(arguments, ',');
if (cache[id]) {
return cache[id];
} else {
cache[id] = fn.apply(this, arguments);
return cache[id];
}
}
};
var mutlPorxy = computeProxy(mult);
var plusProxy = computeProxy(plus);
console.log(mutlPorxy(1, 2, 3, 4));
console.log(plusProxy(1, 2, 3, 4));