javascript基础系列之Reflect
Reflect 提供了拦截Javascript操作的方法,只有静态属性和方法。为了逐步替换掉js引擎提供的全局操作符,如delete, in等操作符
静态方法
Reflect.apply
1 2
| console.log(Reflect.apply("".indexOf, "hello world", ['e']));
|
Reflect.construct
1 2 3 4 5 6
| function Parent() {} const args = [5,6,7]; const p1 = new Parent(...args); const p2 = Reflect.construct(Parent, args) console.log(p1.constructor === p2.constructor);
|
Reflect.defineProperty
1 2 3 4 5 6
| let obj = {} Reflect.defineProperty(obj, "a", { value: 1 }); console.log(obj.a);
|
Reflect.deleteProperty
1 2 3 4 5 6 7
| let obj = { a: 1, b: 2 } Reflect.deleteProperty(obj, "b"); console.log(obj);
|
Reflect.getOwnPropertyDescriptor
1 2 3
| let obj = { a: 1}; console.log(Reflect.getOwnPropertyDescriptor(obj, 'a'));
|
Reflect.has
1 2 3
| const obj1 = { a: 1}; console.log(Reflect.has(obj, "a"));
|
Reflect[isExtensible|preventExtensions]
1 2 3 4 5 6
|
const empty = {}; console.log(Reflect.isExtensible(empty)); Reflect.preventExtensions(empty); console.log(Reflect.isExtensible(empty));
|
Reflect.ownKeys
1 2 3 4 5 6
| let obj = { a: 1, b: 2 } console.log(Reflect.ownKeys(obj));
|
Reflect[set|get]
1 2 3 4 5 6 7 8
|
let obj = {a: 1, b: 2}; console.log(Reflect.get(obj, "b")); let arr = ['a','b', 'c']; console.log(Reflect.get(arr, 1)); Reflect.set(obj, "c", 3); console.log(obj);
|
Reflect.getPrototypeOf
1 2 3 4 5 6 7 8
| const obj = { a: 1}; const proto = Reflect.getPrototypeOf(obj); console.log(proto); console.log(Reflect.getPrototypeOf(proto)); const obj2 = { b: 1}; Reflect.setPrototypeOf(obj, obj2); console.log(obj.__proto__ === obj2);
|
参考文档
Reflect