proxy代理服务_1

发布于:2023-01-24 ⋅ 阅读:(12) ⋅ 点赞:(0) ⋅ 评论:(0)

Proxy代理服务

面试题:

var item = {}
var p = new Proxy(item,{
    set(target,key,value){
        // target : 是这个代理对象,key是属性,value是属性值
        if(value<0 || value >99) throw new RangeError("当前设置超出范围");
        target[key] = value;
    },
    get(target,key){
        target[key]++;
        return target[key];
    }
})
p.o = 12;
console.log(item);
console.log(p.o);//13
console.log(p.o);//14
console.log(p.o);//15
console.log(p.o==16 && p.o==17 && p.o==18)//true

无操作转发

var obj = {
    a:10,
    b:30
}
var p = new Proxy(obj,{});
p.a = 20;
console.log(obj);{a: 20, b: 30}
如果在严格模式下或者type=model,set必须return一个结果出去
证明这个set操作完成
当然这只是在Proxy下有这个操作

var obj = {
    a:10,
    b:30
}
var p = new Proxy(obj,{
    set(target,key,value){
        if(value>99 || value<0) throw RangeError("超出范围")
		// target[key] = value;
		// Reflect.set(target,key,value);
		Reflect.set(...arguments)
    },
    get(target,key){
        return target[key]
    }
})

p.c=100;

第二层无法设置代理,只对属性做检测

Reflect.set(obj,"c",40)
等同于
obj['c'] = 40;

definedProperty

var o = {a:1,b:2}
var p = new Proxy(o,{
    defineProperty(target,key,disc){
        console.log(disc);
        Object.defineProperty(target,key,disc);
        return true;
    }
})
Object.defineProperty(p,"c",{
    value:3,
    writable:true,
})
console.log(o);

新添加时描述对象默认值都为非。
var o = {
   a: 1,
   b: 2
};
var p = new Proxy(o, {
    defineProperty(target, key, disc) {
        if (/^_/.test(key)) disc = {
            enumerable: false,//不可枚举
            value: disc.value,
            writable: disc.writable,
            configurable: disc.configurable
        }
        console.log(disc);
        Object.defineProperty(...arguments);
       //Reflect.defineProperty(...arguments)
        return true;
    }
})
Object.defineProperty(p, "_c", {
    enumerable: true,
    value: 3,
    writable: true,
    configurable: true
})
console.log(o);

如果在代理中同时使用defineProperty和set时,先走set,再走defineProperty

如果改变函数的this指向,bind绑定

var o = {
    a: 1,
    b: 2,
    c:function(){
        document.addEventListener("click",this.d);
    }
};
var p = new Proxy(o, {
    defineProperty(target, key, disc) {
        if (typeof disc.value== "function") 
            disc.value.bind(target);
        console.log(disc);
        // Object.defineProperty(...arguments);
        Reflect.defineProperty(...arguments)
        return true;
    }
})
function fn(){
    console.log("aaa");
    console.log(this);
}
Object.defineProperty(p,"d",{
    value:fn,
})
console.log(o);
o.c();

生成一个div盒子

var divs = new Proxy(div,{
    set(target,key,value){
        if(/width|heigh/.test(key) && !/px$/.test(value)) value+="px";
        target.style[key] = value;
    }
})
divs.width = 500;
divs.height=50;
divs.backgroundColor = "red"