这道Object.prototype的题目中, 为什么每次 obj 会改变呢?
发布于 9 年前 作者 think2011 3724 次浏览 最后一次编辑是 8 年前 来自 问答
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都递减了层次。

4 回复

可能没理解到你的意图。不过obj改变难道不是因为这句:

 obj = obj[el];

@eeandrew 同问。。obj 不是被重新赋值了吗

楼主,我写了个库干这事:https://github.com/alsotang/ettr

@eeandrew @alsotang 啊,没注意,对!是的,非常感谢! 最近通宵做题,有些迷糊了。

回到顶部