CNode

这道Object.prototype的题目中, 为什么每次 obj 会改变呢?

问答
Tthink2011发布于12 年前最后回复12 年前4 回复4849 浏览0 收藏
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)

E
eeandrew#1·12 年前

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

 obj = obj[el];
A
alsotang#2·12 年前
引用 eeandrew可能没理解到你的意图。不过obj改变难道不是因为这句:

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

A
alsotang#3·12 年前

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

T
think2011#4·12 年前
引用 eeandrew可能没理解到你的意图。不过obj改变难道不是因为这句:

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

参与回复
登录后即可参与回复。登录