javascript 缓存代理模式
//缓存代理模式
var computedFn = function() {
console.log('begin')
//console.log(arguments)
var a = 1
for(var i = 0; i < arguments.length; i++) {
a = a * arguments[i]
}
return a
}
//代理对象
var proxyComputed = (function(){
var cache = {}
return function() {
//var args = arguments.join(arguments, ',')
//这里因为arguments只是类数组,不能用数组的[].join()方法
var args = Array.prototype.join.call(arguments, ',')
//如果指定的属性在指定的对象或其原型链中,则in运算符返回true
if(args in cache) {
console.log('从缓存中取')
return cache[args]
}
//func.apply(thisArg, [argsArray]) ,argsArray可选,类型为数组或者类数组对象
return cache[args] = computedFn.apply(null, arguments)
//这样不行,因为computedFn接受参数后会在函数内部合成arguments对象
//return cache[args] = computedFn(arguments)
}
})()
console.log(proxyComputed(1, 2, 3, 4))
console.log(proxyComputed(1, 2, 3, 4))
console.log(proxyComputed(1, 2, 3, 4))
//console.log(computedFn(1, 2, 3, 4))
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
console.log(trees)
console.log("length" in trees)
console.log(Symbol.iterator in trees)
console.log("PI" in Math )
var mycar = {make: "Honda", model: "Accord", year: 1998};
mycar.make = undefined;
delete mycar.make
console.log("make" in mycar); // 返回true
console.log("toString" in {})
console.log({})
//es6 proxy
var person = {
name: '张三'
}
var proxy = new Proxy(person, {
get: function(target, propKey) {
if(propKey in target){
return target[propKey]
} else {
throw new ReferenceError("Prop name \"" + propKey + "\" does not exist. ")
}
}
})
console.log(proxy.name)
console.log(proxy.age)
本文由 dealdot <dealdot#163.com> 创作, Full Stack Developer @ DeepBlue
本文最后编辑时间为: Apr 20, 2021 at 19:47 pm
转载请注明来源