我想知道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
语句中改变其他一些对象。
但是,我不知道这怎么可能。
所以我想这是可能的,如果可能的话,我怎么能这样做。
我自己找到了这个问题的答案:) 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);
}