为什么要返回'这'在导致循环的JavaScript原型中

Why is returning 'this' in a JavaScript prototype causing a loop

本文关键字:循环 JavaScript 原型 返回 为什么      更新时间:2023-09-26

所以我有一个超级简单的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());

在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;

哦。。。。

我认为toString方法中的返回语句应该是return "Dog's name: " + this.name;

var Dog = function(name){
  this.name = name;
}
Dog.prototype.type = function(){
  return this;
}
Dog.prototype.getName = function(){
  //console.log(this.type())
  return "Dog's name: " + this.type(); // <- Calls toString method
}
Dog.prototype.toString = function(){
    return this.name;
};
var spot = new Dog('spot');
console.log(spot.getName());