Proxy 里面set 方法里的this指向?

Proxy 里面set 方法里的this指向?

Proxy 里面set 方法里的this指向?

        const ob = {
            name: "lala",
        }

        const obProxy = new Proxy(ob, {
            set: function(target, key, newValue) {
                console.log('99999', this, this === obProxy);
                target[key] = newValue
            },
            get: function(target, key) {
                return target[key]
            }
        })
        obProxy.name = 123

img


this指向以及原因

在 set 方法里,this 指向的是 obProxy。

这是因为,当你调用 obProxy.name = 123 时,会触发 set 方法的执行,并且 set 方法的 this 关键字就指向 obProxy。

如果你使用箭头函数来定义 set 方法,那么 this 关键字的指向就会变成定义时所在的作用域(在这个例子里是全局)。
当你使用普通函数定义 set 方法时,this 指向的是 obProxy:

const ob = {
  name: "lala",
};
const obProxy = new Proxy(ob, {
  set: function (target, key, newValue) {
    console.log("this:", this); // this: obProxy
    target[key] = newValue;
  },
  get: function (target, key) {
    return target[key];
  },
});
obProxy.name = 123;

而当你使用箭头函数定义 set 方法时,this 指向的是定义时所在的作用域(在浏览器中就是 window 对象):


const ob = {
  name: "lala",
};
const obProxy = new Proxy(ob, {
  set: (target, key, newValue) => {
    console.log("this:", this); // this: window
    target[key] = newValue;
  },
  get: (target, key) => {
    return target[key];
  },
});
obProxy.name = 123;


```javascript
const ops = {
            set: function(target, key, newValue) {
                console.log('99999', this, this === ops); // true
                target[key] = newValue
            },
            get: function(target, key) {
                return target[key]
            }
}
const ob = { name: "lala" }

const obProxy = new Proxy(ob,ops)
obProxy.name = 123

// set 方法是由 ops.set 调用的 。 Proxy 内部发现你修改了 就触发了 ops.set
const obj = {a:111}
const ops = {
            set: function(target, key, newValue) {
                console.log('99999', this, this === obj ); // true
                target[key] = newValue
            }.bind(obj),
            get: function(target, key) {
                return target[key]
            }.bind(obj)
}
const ob = { name: "lala" }
const obProxy = new Proxy(ob,ops)
obProxy.name = 123

```

function 函数 你没有修改它指向的话就是指向调用者。这个知道的把