js Reflect

MDN文档

Reflect 是一个内置的对象,它提供拦截 JavaScript 操作的方法。不可构造(not new)。

Reflect.apply

// Reflect.apply(target, thisArgument, argumentsList)

target, 目标函数。
thisArgument, target函数调用时绑定的this对象。
argumentsList, target函数调用时传入的实参列表,该参数应该是一个类数组的对象。


  function hello (name){
    console.log(`hello ${name}`);
  }

  console.log( Reflect);
  
  Reflect.apply(hello, null, ['ajanuw']);
  // 更上面一样
  Function.prototype.apply.call(hello , null, ['123'] );

  console.log( Reflect.apply( n=> n * n, null, [3]) );// 9

  console.log( Reflect.apply(Number.prototype.toFixed , 2.33, [1]) );// 2.3

Reflect.construct

相当于运行 new


    var arr = Reflect.construct(Array,[1,2,3]);
    console.log( arr);

    function Test(a){
      this.hello = a;
    }
    var obj = Reflect.construct(Test, ['hello']);
    console.log( obj)

Reflect.defineProperty()

和 Object.defineProperty() 类似, Reflect返回boolean, Object成功返回对象,失败抛出错误

  var obj = {};
  if ( Reflect.defineProperty(obj,'name',{value:"ajanuw"}) ){
    console.log( obj);
  }

Reflect.deleteProperty

返回boolean 很像 delete


    var obj = {name:'ajanuw'}
    if( Reflect.deleteProperty(obj,'name') ){
      console.log( obj);
    }

Reflect.get(obj, 'name');

类似 obj['name']

Reflect.getOwnPropertyDescriptor(obj,'name')

返回属性描述符,类似 Object.getOwnPropertyDescriptor()

Reflect.getPrototypeOf(obj)

返回指定对象的原型, 与Object.getPrototypeOf() 方法是一样的

Reflect.has(obj, prop)

返回boolean, 类似 in映射

Reflect.isExtensible(obj), 可扩展返回true

判断一个对象是否可扩展,与 Object.isExtensible()相似

Reflect.set(obj,'name','ajanuw');

类似 obj.name = 'ajanuw', obj['name'] = 'ajanuw'

Reflect.setPrototypeOf(obj, null)

指定对象的原型, 类似 Object.setPrototypeOf()

Reflect.ownKeys( obj )

返回对象自身的属性键组成的数组, 类似 Object.getOwnPropertyNames(obj)


    function obj(){
      this.hello = 'ajanuw'
    }
    obj.prototype.age = 22;

    var x = new obj();
    Reflect.defineProperty(x,'aoo',{
      value: 'aoo'
    })
    
    console.log(Reflect.ownKeys(x ) );// ["hello", "aoo"]

Reflect.preventExtensions(obj);

封闭一个对象,类似 Object.preventExtensions(obj)

posted @ 2017-12-26 12:00  Ajanuw  阅读(1020)  评论(0)    收藏  举报