基础梳理-reflect

40 阅读1分钟

reflect

内置对象,它为可拦截的 JavaScript 操作提供了方法

🌰1 在函数中传递this

// 可以代替传统的apply,使用指定的 this 值和参数调用函数。
function totalPrice(num) {
  let total = 0;

  Object.entries(this).forEach(([key, val]) => {
    total += val * num;
  });

  return total;
}

const stationeryPrice = { pencil: 2, rubber: 1 };

// 下面这三种写法等同,用顺手的就行
const price0 = Function.prototype.apply.call(totalPrice, stationeryPrice, [10])
console.log(price0); // 30

const price1 = totalPrice.apply(stationeryPrice, [10])
console.log(price1); // 30

const price2 = Reflect.apply(totalPrice, stationeryPrice, [10])
console.log(price2); // 30

🌰2 在对象中传递this

在与proxy结合使用中,反射期望的this(实际执行上下文),也说明了为啥vue3里要用到reflect.

const stationery = {
    pencil: 2,

    get value() {
        console.log(this === stationeryProxy)
        return this.pencil
    }
}

const handler = {
    get: function(obj, prop, receiver) {
        // return Reflect.get(obj, prop); // false
        return Reflect.get(obj, prop, receiver);  // true。如果target对象中指定了getter,receiver则为getter调用时的this值。
    }
}

const stationeryProxy = new Proxy(stationery, handler)
console.log(stationeryProxy.value) // 2