JavaScript 反射機(jī)制及 Reflect 詳解

來自 | https://www.cnblogs.com/Leophen/archive/2021/06/02/14838608.html
一、什么是反射機(jī)制
二、Reflect
1、Reflect 定義
Reflect 不是一個(gè)函數(shù)對(duì)象,所以它是不可構(gòu)造的,也就是說它不是一個(gè)構(gòu)造器,不能通過 new 操作符去新建或者將其作為一個(gè)函數(shù)去調(diào)用 Reflect 對(duì)象。
Reflect 成員方法就是 Proxy 處理對(duì)象的默認(rèn)實(shí)現(xiàn)。
const proxy = new Proxy(obj, {get(target, property) {// 如果沒有定義 get 方法,那么默認(rèn)返回的就是 Reflect 的 get 方法return Reflect.get(target, property)}})
2、Reflect API 匯總
Reflect 提供了一套用于操作對(duì)象的 API,我們之前操作對(duì)象可以用 Object 上面的一些方法,也可以用 in、delete 這種操作符,使用 Reflect 就統(tǒng)一了操作方式

3、.apply()
Reflect.apply(target, thisArgument, argumentsList)
target:目標(biāo)函數(shù)(必選)
thisArgument:target 函數(shù)調(diào)用時(shí)綁定的 this 對(duì)象(可選)
argumentsList:target 函數(shù)調(diào)用時(shí)傳入的實(shí)參列表,該參數(shù)應(yīng)該是一個(gè)類數(shù)組的對(duì)象(可選)
① ES5 用法
先指定方法,再去調(diào)用 apply
Math.floor.apply(null, [1.72]) // 1
② ES6 用法
先傳遞 apply,再指定是哪個(gè)方法
Reflect.apply(Math.floor, null, [1.72]) // 1
靜態(tài)掃描時(shí) Math.floor 是沒有被執(zhí)行,等到運(yùn)行時(shí)再動(dòng)態(tài)的將 Math.floor 作為參數(shù)傳進(jìn)來的
③ 實(shí)際應(yīng)用
// ES5 用法let price = 101.5if (price > 100) {price = Math.floor.apply(null, [price])} else {price = Math.ceil.apply(null, [price])}price // 101
// ES6 用法let price = 101.5Reflect.apply(price > 100 ? Math.floor : Math.ceil, null, [price]) // 101
4、.construct()
使用反射的方式去實(shí)現(xiàn)創(chuàng)建類的實(shí)例,類似于 new target(…args)
Reflect.construct(target, argumentsList[, newTarget])
target:被運(yùn)行的目標(biāo)函數(shù)(必選)
argumentsList:調(diào)用構(gòu)造函數(shù)的數(shù)組或者偽數(shù)組(可選)
newTarget:該參數(shù)為構(gòu)造函數(shù), 參考 new.target 操作符,如果沒有 newTarget 參數(shù), 默認(rèn)和 target 一樣(可選)
① ES5 用法
let a = new Date()a.getTime() // 1632632744483
② ES6 用法
let b = Reflect.construct(Date, [])b.getTime() // 1632632744484
5、.defineProperty()
靜態(tài)方法 Reflect.defineProperty() 基本等同于 Object.defineProperty() 方法
Reflect.defineProperty(target, propertyKey, attributes)
target:目標(biāo)對(duì)象(必選)
propertyKey:要定義或修改的屬性的名稱(可選)
attributes:要定義或修改的屬性的描述(可選)
① ES5 用法
const student = {}const r = Object.defineProperty(student, 'name', { value: 'Mike' })student // {name: "Mike"}r // {name: "Mike"}
② ES6 用法
const student = {}const r = Reflect.defineProperty(student, 'name', { value: 'Mike' })student // {name: "Mike"}r // true
區(qū)別在于返回值不同:Object是返回這個(gè)值,Reflect是返回true
PS: 在 W3C 中,以后所有的 Object 上面的方法,都會(huì)慢慢遷移到 Reflect 對(duì)象,可能以后會(huì)在 Object 上面移除這些方法
6、.deleteProperty()
Reflect.deleteProperty 允許你刪除一個(gè)對(duì)象上的屬性,返回一個(gè) Boolean 值表示該屬性是否被成功刪除,它幾乎與非嚴(yán)格的 delete operator 相同
Reflect.deleteProperty(target, propertyKey)
target:刪除屬性的目標(biāo)對(duì)象
propertyKey:將被刪除的屬性的名稱
① ES5 用法
const obj = { x: 1, y: 2 }const a = delete obj.xobj // {y:2}a //true
② ES6 用法
const obj = { x: 1, y: 2 }const a = Reflect.deleteProperty(obj, 'x')obj // {y:2}a //true
7、.get()
Reflect.get() 方法的工作方式,就像從 object (target[propertyKey]) 中獲取屬性,但它是作為一個(gè)函數(shù)執(zhí)行的
Reflect.get(target, propertyKey[, receiver])
① ES5 用法
const obj = { x: 1, y: 2 }obj.x //1obj['x'] //1
② ES6 用法
const obj = { x: 1, y: 2 }Reflect.get(obj, 'x') // 1Reflect.get(['a', 'b', 'c'], 1) // b
8、.getOwnPropertyDescriptor()
靜態(tài)方法 Reflect.getOwnPropertyDescriptor() 與 Object.getOwnPropertyDescriptor() 方法相似
如果在對(duì)象中存在,則返回給定的屬性的屬性描述符,否則返回 undefined
Reflect.getOwnPropertyDescriptor(target, propertyKey)
① ES5 用法
const obj = { x: 1, y: 2 }Object.getOwnPropertyDescriptor(obj, 'x')// {value:1, writable:true, enumerable:true, configurable:true}
② ES6 用法
const obj = { x: 1, y: 2 }Reflect.getOwnPropertyDescriptor(obj, 'x')// {value:1, writable:true, enumerable:true, configurable:true}Reflect.getOwnPropertyDescriptor({ x: 'hello' }, 'y')//undefinedReflect.getOwnPropertyDescriptor([], 'length')// {value:0, writable:true, enumerable:false, configurable:false}
③ 對(duì)比
如果 Reflect.getOwnPropertyDescriptor 的第一個(gè)參數(shù)不是一個(gè)對(duì)象(一個(gè)原始值),那么將造成 TypeError 錯(cuò)誤
而對(duì)于 Object.getOwnPropertyDescriptor,非對(duì)象的第一個(gè)參數(shù)將被強(qiáng)制轉(zhuǎn)換為一個(gè)對(duì)象處理
Reflect.getOwnPropertyDescriptor("foo", 0);//TypeError:"foo"isnotnon-nullobjectObject.getOwnPropertyDescriptor("foo", 0);// { value:"f", writable:false, enumerable:true, configurable:false }
9、.getPrototypeOf()
靜態(tài)方法 Reflect.getPrototypeOf() 與 Object.getPrototypeOf() 方法是一樣的,都是返回指定對(duì)象的原型(即,內(nèi)部的 [[Prototype]] 屬性的值)
Reflect.getPrototypeOf(target)
① ES5 用法
const d = New Date()Object.getPrototypeOf(d)// {constructor:?, toString:?, toDateString:?, toTimeString:?, toISOString:?, …}
② ES6 用法
const d = New Date()Reflect.getPrototypeOf(d)// {constructor:?, toString:?, toDateString:?, toTimeString:?, toISOString:?, …}
10、.has()
判斷一個(gè)對(duì)象是否存在某個(gè)屬性,和 in 運(yùn)算符 的功能完全相同
Reflect.has(target, propertyKey)
const obj = { x: 1, y: 2 }Reflect.has(obj, 'x') //trueReflect.has(obj, 'z') //false
11、.isExtensible()
判斷一個(gè)對(duì)象是否可擴(kuò)展
Reflect.isExtensible 與 Object.isExtensible 方法一樣,都是判斷一個(gè)對(duì)象是否可擴(kuò)展 (即是否能夠添加新的屬性)
Reflect.isExtensible(target)
const obj = { x: 1, y: 2 }Reflect.isExtensible(obj) //trueObject.freeze(obj) //阻止新屬性添加到對(duì)象obj.z = 3Reflect.isExtensible(obj) //falseobj // {x:1, y:2}
12、.ownKeys()
判斷對(duì)象自身屬性
Reflect.ownKeys 方法返回一個(gè)由目標(biāo)對(duì)象自身的屬性鍵組成的數(shù)組,它的返回值等同于 `Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))
Reflect.ownKeys(target)
const obj = { x: 1, y: 2 }Reflect.ownKeys(obj) // ["x", "y"]Reflect.ownKeys([]) // ["length"]Reflect.ownKeys([1, 2]) // ["0", "1", "length"]
13、.preventExtensions()
阻止新屬性添加到對(duì)象,等同于Object.freeze()
Reflect.preventExtensions 方法阻止新屬性添加到對(duì)象,例如:防止將來對(duì)對(duì)象的擴(kuò)展被添加到對(duì)象中,與 Object.preventExtensions() 方法一致
const obj = { x: 1, y: 2 }Reflect.isExtensible(obj) //trueReflect.preventExtensions(obj) //阻止新屬性添加到對(duì)象obj.z = 3Reflect.isExtensible(obj) //falseobj // {x:1, y:2}
14、.set()
寫數(shù)據(jù)
Reflect.set 方法允許你在對(duì)象上設(shè)置屬性,用來給屬性賦值,類似 property accessor 的語法,但它是以函數(shù)的方式
Reflect.set(target, propertyKey, value[, receiver])
const obj = { x: 1, y: 2 }Reflect.set(obj, 'z', 4)obj // {x:1, y:2, z:4}const arr = ['apple', 'pear']Reflect.set(arr, 1, 'banana')arr // ["apple", "banana"]
15、.setPrototypeOf()
Reflect.setPrototypeOf 方法改變指定對(duì)象的原型 (即內(nèi)部的 [[Prototype]] 屬性值)
Reflect.setPrototypeOf(target, prototype)
const arr = ['apple', 'pear']Reflect.getPrototypeOf(arr)// [constructor: ?, concat: ?, copyWithin: ?, fill: ?, find: ?,…]Reflect.setPrototypeOf(arr, String.prototype)Reflect.getPrototypeOf(arr)// String {"", constructor: ?, anchor: ?, big: ?, blink: ?, …}
本文完~
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

