Nodejs中这道关于Object.prototype的题目,为什么每次 obj 会改变呢?
Nodejs中这道关于Object.prototype的题目,为什么每次 obj 会改变呢?
Object.prototype.hash = function(string) {
var obj = this;
string.split(".").forEach(function(el) {
console.log(obj); // 为什么每次 obj 会改变呢?
try {
obj = obj[el];
}
catch(e) {
obj = undefined;
}
});
return obj;
}
// 测试用例
var obj = {
person: {
name: ‘joe’,
history: {
hometown: ‘bratislava’,
bio: {
funFact: ‘I like fishing.’
}
}
}
};
console.log(obj.hash(‘person.name’));
console.log(obj.hash(‘person.history.bio’));
console.log(obj.hash(‘person.history.homeStreet’));
console.log(obj.hash(‘person.animal.pet.needNoseAntEater’));
发现每一次循环,obj都递减了层次。
可能没理解到你的意图。不过obj改变难道不是因为这句:
obj = obj[el];
楼主,我写了个库干这事:https://github.com/alsotang/ettr
在你的代码中,obj
的值在 string.split(".").forEach
循环中不断变化。每次迭代时,obj
都会被重新赋值为当前路径上的下一个对象属性。如果路径不存在,则 obj
被设置为 undefined
。
这是因为在每次迭代中,你都在修改 obj
的值:
obj = obj[el];
这里 obj
会被更新为其属性 el
的值。因此,在多次迭代之后,obj
可能不再指向原始对象 this
(即传入 hash
方法的对象)。
为了更清楚地理解这个问题,我们可以添加一些日志来查看 obj
在每次迭代中的变化情况。
下面是带有详细日志输出的代码示例:
Object.prototype.hash = function (string) {
let obj = this;
string.split(".").forEach(function (el) {
console.log(`Current obj:`, obj);
try {
obj = obj[el];
console.log(`After accessing '${el}':`, obj);
} catch (e) {
obj = undefined;
console.log(`Caught exception, setting obj to undefined`);
}
});
return obj;
};
// 测试用例
var obj = {
person: {
name: 'joe',
history: {
hometown: 'bratislava',
bio: {
funFact: 'I like fishing.',
},
},
},
};
console.log(obj.hash('person.name')); // 输出 'joe'
console.log(obj.hash('person.history.bio')); // 输出 'I like fishing.'
console.log(obj.hash('person.history.homeStreet')); // 输出 undefined
console.log(obj.hash('person.animal.pet.needNoseAntEater')); // 输出 undefined
通过这段代码,你可以看到每次迭代时 obj
的值是如何变化的。