码迷,mamicode.com
首页 > 其他好文 > 详细

学些ES6:反射

时间:2015-08-30 20:56:10      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:

Reflect:

基础:

let Class = class {};

Reflect.construct(Class) instanceof Class // true

let obj = {x: 23};

Reflect.get(obj, ‘x‘) // 23

Reflect.has(obj, ‘x‘) // true

apply:

执行函数:

let fn = () => {return 42;};

Reflect.apply(fn) // 42

指定context:

class FourtyTwo {
constructor() { this.value = 42}
fn() {return this.value}
}

let instance = new FourtyTwo();

const fourtyTwo = Reflect.apply(instance.fn, instance); // 42

以数组形式传递参数:

let emptyArrayWithFiveElements = Reflect.apply(Array, [], [5]); // new Array(5)

emptyArrayWithFiveElements.fill(42) // [42, 42, 42, 42, 42]

getPrototypeOf:

const viaObject = Object.getPrototypeOf({});
const viaReflect = Reflect.getPrototypeOf({});

Reflect.getPrototypeOf() // TypeError

const aSet = new Set();

Reflect.getPrototypeOf(aSet) // Set.prototype

let arr = [];
Reflect.getPrototypeOf(arr) // Array.prototype;

construct:

let aFunction = () => {};

Reflect.construct(aFunction) 

const aClass = class {};

Reflect.construct(aClass)

let arrayLike = {get length() { return 2 }};

Reflect.construct(aClass, arrayLike)

let realArray = [];

Reflect.construct(aClass, realArray)

defineProperty:

let obj = {};
Reflect.defineProperty(obj, ‘prop‘, {}); // ‘prop‘ in obj

let obj = {};
const sym = Symbol.for(‘prop‘);
Reflect.defineProperty(obj, sym, {}); // sym in obj

let obj = {};
var success = Reflect.defineProperty(obj, ‘prop‘, {value: ‘value‘}); // obj.prop: ‘value‘, success: true

 

学些ES6:反射

标签:

原文地址:http://www.cnblogs.com/benben77/p/4771407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!