Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

js如何使用Proxy代理,实现读取window下的变量时改变其默认行为

这是一道题,实现console.log(a == 2 && a === 3 && a == 4)为true:
用Object.defineProperty的方式去实现不难,然后不都说可以用Proxy去实现Object.defineProperty的功能嘛,所以请问怎么用Proxy去实现?试过window = new Proxy()是不行的,还是会报错a为undefined,有没有大佬说一下

let index = 2
Object.defineProperty(window, 'a', {
get: function () {
  return index++
},
})
console.log(a == 2 && a === 3 && a == 4) //true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Proxy 并不改变直接调用 target 本身的 getter/setter……而是需要通过 Proxy 访问了……

要不怎么叫代理呢……

非要写的话这么做是可以的:

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...