为什么在JavaScript原型中返回'this'会导致循环

时间:2016-05-16 17:22:36

标签: javascript oop prototype

所以我有这个超级简单的JS对象,我正在搞乱,我遇到了一些我无法弄清楚的东西。当我运行它时,obj.toString被反复调用,直到我收到“最大调用堆栈大小错误”。但是,如果我将obj.type中的'this'替换为'this.name',一切正常。我意识到我通常不会只返回'this',但为什么我会在循环中陷入困境?

var Dog = function(name){
  this.name = name;
}
Dog.prototype.type = function(){
  return this;
}
Dog.prototype.toString = function(){
  //console.log(this.type())

  return "Dog's name: " + this.type();
}

var spot = new Dog('spot');
console.log(spot.toString());

3 个答案:

答案 0 :(得分:1)

在javascript中对对象进行字符串化时,会调用toString()函数。

在这种情况下,您有一个自定义toString()函数。凉。

所以让我们追踪一下:

  1. console.log(spot.toString())
  2. return "Dog's name: " + this.type();
  3. return this;
  4. // Hmmmm. How do we add "this" to our string. Easy we call toString().
  5. return "Dog's name: " + this.type();
  6. return this;
  7. // Hmmmm. How do we add "this" to our string. Easy we call toString().
  8. return "Dog's name: " + this.type();
  9. return this;
  10. 哦,哦......

答案 1 :(得分:0)

我相信toString方法中的退货声明应为return "Dog's name: " + this.name;

答案 2 :(得分:-1)

obj.SetValue(ForecastPoint.ValueProperty, value)