es6 --- >Proxy的属性(get、set除外)

apply(): 拦截函数的调用、call和apply操作

var target = function () { return 'I am the target';};
var handler = {
    apply: function () {
        reuturn 'I am the proxy';
    }
};

var p = new Proxy(target, handler);
p();  // " I am the proxy"

has(): 判断对象是否具有某个属性,典型的操作就是in运算符

var handler ={
    has (target, key) {
        if ( key[0] === '_') {
            return false;
        }
        return key in target;
    }
};
var target = { _prop: 'foo', prop: 'foo' };
var proxy = new Proxy(target, handler);
'_prop' in proxy // false

// 注:has拦截对for...in循环不生效
let stu1 = {name: '张三', score: 59};
let stu2 = {name: '李四', score: 99};

let handler = {
    has (target, prop) {
         if (prop === 'score' && target[prop] < 60) {
             console.log(target.name, '不及格');
             return false;
         }
         return prop in target;
     }
}
let oproxy1 = new Proxy(stu1, handler);
let oproxy2 = new Proxy(stu2, handler);
    
'score' in oproxy1
// 张三不及格
// false     

construct(): 用于拦截new命令

var p = new Proxy(function () {}, {
    construct: function (target, args) {
        console.log('called: ' + args.join(', ')):
        return { value: args[0] *10};
    }
});

(new p(1)).value
// "called: 1"
// 10

deleteProperty(): 拦截delete操作

var handler = {
    deleteProperty (target, key) {
        invariant(key, 'delete');
        return true;
    }
};
function invariant (key, action) {
    if (key[0] === '_') {
        throw new Error('Invalid attempt to',action,'private', key,'property');
    }
}
var target = {_prop: 'foo' };
var proxy = new Proxy(target, handler);
delete proxy._prop
// Error: Invalid attempt to delete private "_prop" property

defineProperty(): 拦截Object.defineProperty操作
getOwnPropertyDescriptor(): 拦截Object.getOwnPropertyDescriptor()
getPrototypeOf(): 拦截获取对象原型

var proto = {};
var p = new Proxy({}, {
    getPrototypeOf(target) {
        return proto;
    }
});
Object.getPrototypeOf(p)  === proto // true

isExtensible(): 拦截Object.isExtensible操作
ownKeys(): 拦截对象自身属性的读取操作

// 下面的例子是拦截第一个字符为下画线的属性名
let target = {
    _bar: 'foo',
    _prop: 'bar',
    prop: 'baz'
};

let handler = {
    ownKeys (target) {
        return Reflect.ownKeys(target).fliter(key => key[0] !== '_');
    }
};

let proxy = new Proxy(target, handler);
for ( let key of Object.keys(proxy)) {
    console.log(target[key]);
}
// "baz"
// 注:有三类属性会被 ownKeys方法自动过滤:
// ·目标对象不存在的属性
// ·属性名为Symbol值
// ·不可遍历的属性

// 注:ownKeys方法返回的数组成员只能是字符串或 Symbol值.

preventExtensions(): 拦截Object.preventExtensions()
setPrototypeOf(): 拦截Object.setPrototypeOf()

参考《ES6标准入门》(第三版) P242~P255

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值