在javascript中,“for ... in”语句如何产生副作用?

问题描述 投票:3回答:1

我想知道for .. in有什么副作用吗?

let arr = [1.1, 2.2];
let obj = {x: 1, y: 1, z: 1};
for(let prop in obj) {
    ...
}

考虑上面的代码片段,是否有可能在arr语句中更改for .. in中的某些元素而不是在循环体中?

我目前正在使用JavaScriptCore JIT编译器,DFG假设GetPropertyEnumerator有副作用,我知道它可以在for .. in语句中改变其他一些对象。 但是,我不知道这怎么可能。 所以我想这是可能的,如果可能的话,我怎么能这样做。

javascript side-effects javascriptcore
1个回答
1
投票

我自己找到了这个问题的答案:) https://github.com/WebKit/webkit/commit/243a17dd57da84426316502c5346766429f2456d 上面的提交日志对我很有帮助!

Proxy对象的成员名为getPrototypeOf。 通过使用这个getPrototypeOf,我可以在for .. in语句中的属性查找阶段修改一些对象。

let a = {x: 1, y: 2, z: 3};
a.__proto__ = {xx: 1, yy: 2, zz: 3};

for(let i in a) {
    print(i);
}

以上是一个简单的例子。 for .. in语句查找Object a的属性,然后按照__proto__链接。 在这种情况下,Proxy的getPrototypeOf__proto__查找的陷阱。 示例如下。

let a = {
  x: 1,
  y: 2,
  z: 3
};
let p = new Proxy(a, {
  getPrototypeOf: function() {
    console.log("getPrototypeOf - side effects can be caused here");
    return {
      a: 1,
      b: 2
    };
  }
});

for (let i in p) {
  console.log(i);
}
© www.soinside.com 2019 - 2024. All rights reserved.