首页 > 其他 > 详细

Proxy this 问题

时间:2020-03-25 11:14:31      阅读:71      评论:0      收藏:0      [点我收藏+]

在 Proxy 代理的情况下,目标对象内部的this关键字会指向 Proxy 代理。

const target = {
  m: function () {
    console.log(this === proxy);
  }
};
const handler = {};

const proxy = new Proxy(target, handler);

target.m() // false
proxy.m()  // true
上面代码中,一旦proxy代理target.m,后者内部的this就是指向proxy,而不是target。

由于this指向的变化,导致 Proxy 无法代理目标对象。 

const _name = new WeakMap();

class Person {
  constructor(name) {
    _name.set(this, name);
  }
  get name() {
    return _name.get(this);
  }
}

const jane = new Person(‘Jane‘);
jane.name // ‘Jane‘

const proxy = new Proxy(jane, {});
proxy.name // undefined 目标对象janename属性,实际保存在外部WeakMap对象_name上面,通过this键区分。由于通过proxy.name访问时,this指向proxy,导致无法取到值,所以返回undefined

Proxy 也无法代理这些原生对象的属性。  

const target = new Date();
const handler = {};
const proxy = new Proxy(target, handler);

proxy.getDate();
// TypeError: this is not a Date object.
getDate方法只能在Date对象实例上面拿到,如果this不是Date对象实例就会报错。

this绑定原始对象,就可以解决这个问题。
const target = new Date(‘2015-01-01‘);
const handler = {
  get(target, prop) {
    if (prop === ‘getDate‘) {
      return target.getDate.bind(target);
    }
    return Reflect.get(target, prop);
  }
};
const proxy = new Proxy(target, handler);

proxy.getDate() // 1

  

 

Proxy this 问题

原文:https://www.cnblogs.com/blogZhao/p/12564346.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!