JS 反射機(jī)制及 Reflect
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
作者 | Leophen
來(lái)源 | urlify.cn/yy6biy
一、什么是反射機(jī)制
反射機(jī)制是在編譯階段不知道是哪個(gè)類被加載,而是在運(yùn)行的時(shí)候才加載、執(zhí)行。
也就是說(shuō),反射機(jī)制指的是程序在運(yùn)行時(shí)能夠獲取自身的信息。js 中的 apply 就是反射機(jī)制。
二、Reflect
1、Reflect 定義
Reflect 是一個(gè)內(nèi)建的對(duì)象,用來(lái)提供方法去攔截 JavaScript 的操作。Reflect 不是一個(gè)函數(shù)對(duì)象,所以它是不可構(gòu)造的,也就是說(shuō)它不是一個(gè)構(gòu)造器,不能通過(guò) new 操作符去新建或者將其作為一個(gè)函數(shù)去調(diào)用 Reflect 對(duì)象。Reflect 的所有屬性和方法都是靜態(tài)的。
Reflect 內(nèi)部封裝了一系列對(duì)對(duì)象的底層操作Reflect 成員方法就是 Proxy 處理對(duì)象的默認(rèn)實(shí)現(xiàn)
const proxy = new Proxy(obj, {
get(target, property) {
// 如果沒(méi)有定義 get 方法,那么默認(rèn)返回的就是 Reflect 的 get 方法
return Reflect.get(target, property)
}
})
2、Reflect API 匯總
Reflect 提供了一套用于操作對(duì)象的 API,我們之前操作對(duì)象可以用 Object 上面的一些方法,也可以用 in、delete 這種操作符,使用 Reflect 就統(tǒng)一了操作方式
| handler ?法 | 默認(rèn)調(diào)? | 功能 |
|---|---|---|
| get | Reflect.get() | 獲取對(duì)象身上某個(gè)屬性的值 |
| set | Reflect.set() | 在對(duì)象上設(shè)置屬性 |
| has | Reflect.has() | 判斷一個(gè)對(duì)象是否存在某個(gè)屬性 |
| deleteProperty | Reflect.deleteProperty() | 刪除對(duì)象上的屬性 |
| getProperty | Reflect.getPrototypeOf() | 獲取指定對(duì)象原型的函數(shù) |
| setProperty | Reflect.setPrototypeOf() | 設(shè)置或改變對(duì)象原型的函數(shù) |
| isExtensible | Reflect.isExtensible() | 判斷一個(gè)對(duì)象是否可擴(kuò)展 (即是否能夠添加新的屬性) |
| preventExtensions | Reflect.preventExtensions() | 阻止新屬性添加到對(duì)象 |
| getOwnPropertyDescriptor | Reflect.getOwnPropertyDescriptor() | 獲取給定屬性的屬性描述符 |
| defineProperty | Reflect.defineProperty() | 定義或修改一個(gè)對(duì)象的屬性 |
| ownKeys | Reflect.ownKeys() | 返回由目標(biāo)對(duì)象自身的屬性鍵組成的數(shù)組 |
| apply | Reflect.apply() | 對(duì)一個(gè)函數(shù)進(jìn)行調(diào)用操作,同時(shí)可以傳入一個(gè)數(shù)組作為調(diào)用參數(shù) |
| construct | Reflect.construct() | 對(duì)構(gòu)造函數(shù)進(jìn)行 new 操作,實(shí)現(xiàn)創(chuàng)建類的實(shí)例 |
| .preventExtensions | Reflect.preventExtensions() | 阻止新屬性添加到對(duì)象 |
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 是沒(méi)有被執(zhí)行,等到運(yùn)行時(shí)再動(dòng)態(tài)的將 Math.floor 作為參數(shù)傳進(jìn)來(lái)的
③ 實(shí)際應(yīng)用
// ES5 用法
let price = 101.5
if (price > 100) {
price = Math.floor.apply(null, [price])
} else {
price = Math.ceil.apply(null, [price])
}
price // 101
// ES6 用法
let price = 101.5
Reflect.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 操作符,如果沒(méi)有 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
這兩個(gè)方法效果上來(lái)看是一摸一樣的,都可以改變一個(gè)對(duì)象的值
區(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.x
obj // {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 // 1
obj['x'] // 1
② ES6 用法
const obj = { x: 1, y: 2 }
Reflect.get(obj, 'x') // 1
Reflect.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')
// undefined
Reflect.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" is not non-null object
Object.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') // true
Reflect.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) // true
Object.freeze(obj) // 阻止新屬性添加到對(duì)象
obj.z = 3
Reflect.isExtensible(obj) // false
obj // {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ì)象,例如:防止將來(lái)對(duì)對(duì)象的擴(kuò)展被添加到對(duì)象中,與 Object.preventExtensions() 方法一致
Reflect.preventExtensions(target)
const obj = { x: 1, y: 2 }
Reflect.isExtensible(obj) // true
Reflect.preventExtensions(obj) // 阻止新屬性添加到對(duì)象
obj.z = 3
Reflect.isExtensible(obj) // false
obj // {x: 1, y: 2}
14、.set()
寫數(shù)據(jù)Reflect.set 方法允許你在對(duì)象上設(shè)置屬性,用來(lái)給屬性賦值,類似 property accessor 的語(yǔ)法,但它是以函數(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: ?, …}


