本文實例講述了ES6 proxy和reflect的使用方法。分享給大家供大家參考,具體如下:
proxy和reflect都是es6為了更好的操作對象而提供的新的API,接下來探討一下二者的作用,聯系。
設計proxy,reflect的作用:
proxy的作用:
Proxy的設計目的在于(修改編程語言),修改某些操作方法的默認行為,
等同于在語言層面作出修改,是元編程(meta programming) 例如修改set,get方法
reflect的作用:
1,映射一些明顯屬于對象語言內部的方法,目前是共存于Object和Reflect上,未來只在Reflect上
2,修改一些Object上的方法返回的結果,減少異常拋出,使其變得更加合理
3,讓Object操作都變成函數行為(主要的作用)
4,Reflect對象的方法與Proxy對象的方法一一對應(主要的作用)
proxy和reflect的方法:
proxy的實例方法:
| get() | set() | apply() | has() | cunstruct() | deleteProperty() | defineProperty() |
| getOwnPropertyDescriptor() | getPrototypeOf() | isExtensible() | ownKeys(), | preventExtensions() | setPrototypeOf() |
var person = { name: "張三"}; var proxy = new Proxy(person, { get: function(target, property) { if (property in target) { return target[property]; } else { throw new ReferenceError("Property /"" + property + "/" does not exist."); } }});注:目標對象內部的this關鍵字會指向 Proxy 代理
自身方法:Proxy.revocable方法返回一個可取消的 Proxy 實例
reflect的靜態方法:
和proxy相對應,reflect有13個靜態方法,分別一一對應于proxy的實例方法
| Reflect.apply(target, thisArg, args) | Reflect.construct(target, args) |
| Reflect.get(target, name, receiver) | Reflect.set(target, name, value, receiver) |
| Reflect.defineProperty(target, name, desc) | Reflect.deleteProperty(target, name) |
| Reflect.has(target, name) | Reflect.ownKeys(target) |
| Reflect.isExtensible(target) | Reflect.preventExtensions(target) |
| Reflect.getOwnPropertyDescriptor(target, name) | Reflect.getPrototypeOf(target) |
| Reflect.setPrototypeOf(target, prototype) |
新聞熱點
疑難解答
圖片精選