Reflect 簡介:
Reflect 這個對象在早期 Node(v4.4.3)中尚未實現,Babel(6.7.7)也沒有,而新版本 Chrome 已支持,Firefox 更是很早就支持了 Proxy 和 Reflect。若想讓 Node 支持 Reflect,可以安裝 harmony-reflect。
Reflect 不是構造函數,使用時直接通過 Reflect.method() 調用。它的很多方法與 Proxy 相近,而且多數 Reflect 方法在原生 Object 上也已有對應實現。
為什麼要用 Reflect
下面列舉幾個使用 Reflect 的理由:
1)更有用的返回值。Reflect 的一些方法與 ES5 的 Object 方法相同,比如 Reflect.getOwnPropertyDescriptor 和 Reflect.defineProperty。不過 Object.defineProperty(obj, name, desc) 執行成功會返回 obj,出錯則拋異常;而 Reflect.defineProperty 只返回 true 或 false 表示屬性是否設置成功,代碼可重構為:
try { Object.defineProperty(obj, name, desc); // property defined successfully } catch (e) { // possible failure (and might accidentally catch the wrong exception) }重構後:
if (Reflect.defineProperty(obj, name, desc)) { // success } else { // failure }其餘如 Reflect.set、Reflect.deleteProperty、Reflect.preventExtensions、Reflect.setPrototypeOf 都可作類似重構。
2)函數操作。若要判斷 obj 是否定義或繼承了屬性 name,ES5 中寫 name in obj;刪除屬性寫 delete obj[name]。這些雖簡短明確,但使用時往往需要再封裝。有了 Reflect,直接調用 Reflect.has(obj, name)、Reflect.deleteProperty(obj, name) 即可。
3)更可靠的函數式執行。在 ES 中,要執行函數 f、傳入參數 args 並綁定 this,通常寫:
f.apply(obj, args)
但 f 的 apply 可能被用戶重定義,所以更穩妥的寫法是:
Function.prototype.apply.call(f, obj, args)
這段代碼冗長且不好懂。有了 Reflect,可以寫得更簡潔:
Reflect.apply(f, obj, args)
4)可變參數形式的構造函數。若想通過不定長參數實例化一個構造函數,ES6 可用擴展符號:
var obj = new F(...args)
但在不支持擴展符的環境下,只能用 F.apply 或 F.call 傳不同參數,而 F 是構造函數時就比較棘手。有了 Reflect,可以這樣寫:
var obj = Reflect.construct(F, args)
5)控制訪問器的 this。ES5 中讀取或設置屬性這樣寫:
var name = ... // get property name as a string obj[name] // generic property lookup obj[name] = value // generic property
Reflect.get 和 Reflect.set 能做同樣的事,還多了一個 receiver 參數,允許設置 setter/getter 的上下文 this:
var name = ... // get property name as a string Reflect.get(obj, name, wrapper) // if obj[name] is an accessor, it gets run with `this === wrapper` Reflect.set(obj, name, value, wrapper)
例如讓訪問器把 this 重定向到 wrapper:
var obj = { set foo(value) { return this.bar(); }, bar: function() { alert(1); } }; var wrapper = { bar : function() { console.log("wrapper"); } } Reflect.set(obj, "foo", "value", wrapper);6)避免直接訪問 __proto__。ES5 用 Object.getPrototypeOf(obj) 訪問原型,ES6 提供了 Reflect.getPrototypeOf(obj) 和 Reflect.setPrototypeOf(obj, newProto) 作為訪問與設置原型的新方法。
Reflect.apply 的用法
Reflect.apply 就是 ES5 中 Function.prototype.apply() 的替身,執行時需要三個參數:第一個是要執行的函數;第二個是函數的上下文 this;第三個是作為參數的數組或偽數組。
示例:
Reflect.apply(Math.floor, undefined, [1.75]); // 1 Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]); // "hello" Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index; // 4 Reflect.apply("".charAt, "ponies", [3]); // "i"它還可與 Proxy 聯合使用,例如在構造攔截器中調用 target.prototype.run。
Reflect.construct 的用法
Reflect.construct 就是通過傳參形式實例化構造函數,第一個參數為構造函數,第二個為參數組成的數組或偽數組:
var Fn = function(arg) { this.args = [arg] }; console.log( new Fn(1), Reflect.construct(Fn,[1]) ); // 輸出是一樣的 var d = Reflect.construct(Date, [1776, 6, 4]); d instanceof Date; // true d.getFullYear(); // 1776它還可以傳第三個參數(一個超類),讓新元素繼承該超類,從而實現「繼承數組但又有自己方法」的特殊數組:
var Fn = function() { Array.apply(this, arguments); this.shot = ()=> { console.log("heheda"); }; }; var arr = Reflect.construct(Fn, [])Reflect.defineProperty 的用法
Reflect.defineProperty 返回布爾值,而直接賦值會返回整個對象,失敗時會拋錯。當對象被 preventExtensions 後,Object.defineProperty 定義新屬性會拋錯,而 Reflect.defineProperty 只是返回 false:
var obj = {}; Object.preventExtensions(obj); console.log( Reflect.defineProperty(obj, "x", {value:101}) ) //返回false反之,直接賦值無論成功與否都返回所設定的值,除非手動確認:
var obj = {}; Object.preventExtensions(obj); console.log( obj.aa = 1 ); //1 console.log(obj.aa) //undefinedReflect.deleteProperty 的用法
它與 delete obj.xx 的操作結果一致,只是形式不同(一個是操作符,一個是函數調用):
Reflect.deleteProperty(Object.freeze({foo: 1}), "foo"); // false delete Object.freeze({foo: 1}).foo; // falseReflect.get 的用法
兩個必須參數:目標對象 obj 與屬性名,第三個可選參數作為讀取器的上下文 this:
var obj = {}; obj.foo = 1; console.log( obj.foo ); //1 console.log( Reflect.get(obj, "foo") ) //1Reflect.getOwnPropertyDescriptor 的用法
用於獲取屬性描述,與 Object.getOwnPropertyDescriptor 的區別在於:前者不會對非對象參數做包裝,後者會:
Reflect.getOwnPropertyDescriptor("hello",0); // 拋出異常 Object.getOwnPropertyDescriptor("hello",0); // {value: "h", writable: false, enumerable: true, configurable: false}Reflect.getPrototypeOf 的用法
與 Object.getPrototypeOf 一樣,返回一個對象的原型:
Reflect.getPrototypeOf({}); // Object.prototype Reflect.getPrototypeOf(Object.prototype); // null Reflect.getPrototypeOf(Object.create(null)); // nullReflect.has 的用法
它有點像 in 操作符,並可與 Proxy 的 has 攔截器配合:
obj = new Proxy({}, { has(t, k) { return k.startsWith("door"); } }); Reflect.has(obj, "doorbell"); // true Reflect.has(obj, "dormitory"); // falseReflect.isExtensible 的用法
與 Object.isExtensible 的區別是:參數不合法時,前者拋錯,後者只返回 true 或 false:
Reflect.isExtensible(1); // 拋錯 Object.isExtensible(1); // 返回false
Reflect.ownKeys 的用法
Object 並沒有 ownKeys 方法,Reflect.ownKeys 用於返回對象的所有 keys(含 Symbol):
console.log(Reflect.ownKeys({"a":0,"b":1,"c":2,"d":3})); // ["a", "b", "c", "d"] console.log(Reflect.ownKeys([])); // ["length"]其排序規則是:先數字(按大小排序),再字符串(按插入順序),最後是 Symbol 類型(按插入順序)。這與給對象賦值時 key 的排列規則一致。
Reflect.preventExtensions 的用法
與 Object.preventExtensions 略有區別:Reflect.preventExtensions 參數不是對象時會拋錯。
Reflect.preventExtensions(1); // TypeError: 1 is not an object Object.preventExtensions(1); // 返回:1
Reflect.set 的用法
與 get 類似,還可傳第四個參數作為 setter 的 this:
var obj = {}; Reflect.set(obj, "prop", "value"); // true console.log( obj.prop ); // "value" var arr = ["duck", "duck", "duck"]; Reflect.set(arr, 2, "goose"); // true console.log( arr[2] ); // "goose"Reflect.setPrototypeOf 的用法
與 Object.setPrototypeOf 類似,用於設置對象原型(即修改 __proto__)。若對象被凍結或原型鏈形成循環依賴,則返回 false:
Reflect.setPrototypeOf({}, Object.prototype); // true Reflect.setPrototypeOf(Object.freeze({}), null); // false var target = {}; var proto = Object.create(target); Reflect.setPrototypeOf(target, proto); // false總的來說,Reflect 讓 JS 的對象操作更函數化、返回值語義更清晰,也與 Proxy 形成了良好的互操作基礎,是 ES6 中值得深入掌握的特性。