美文网首页
Proxy this 指向

Proxy this 指向

作者: antlove | 来源:发表于2020-03-25 19:46 被阅读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

通过bind使方法中的this指向原始对象

const target = {
  m: function () {
    console.log(this === target);
  }
};
const handler = {
    get(target, propName) {
        return target[propName].bind(target);
    }
};

const proxy = new Proxy(target, handler);

target.m() // true
proxy.m()  // true

相关文章

网友评论

      本文标题:Proxy this 指向

      本文链接:https://www.haomeiwen.com/subject/prnxuhtx.html