简体   繁体   English

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

[英]Why is returning 'this' in a JavaScript prototype causing a loop

So I have this super simple JS Object I was messing around with and I came across something I can't figure out. 因此,我遇到了这个超级简单的JS对象,遇到了一些我不知道的问题。 When I run this, obj.toString is called over and over until I receive a 'Maximum call stack size error'. 运行此命令时,一遍又一遍地调用obj.toString,直到收到“最大调用堆栈大小错误”。 However, if I replace 'this' in the obj.type return to 'this.name', everything works fine. 但是,如果我在obj.type中将“ this”替换为“ this.name”,则一切正常。 I realize I wouldn't normally return just 'this', but why is it getting caught in a loop when I do? 我意识到我通常不会只返回“ 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());

When you stringify an object in javascript, the toString() function is called. 在javascript中对对象进行字符串化时,将调用toString()函数。

In this case, you have a custom toString() function. 在这种情况下,您有一个自定义的toString()函数。 Cool. 凉。

So let's trace this: 因此,让我们跟踪一下:

  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;

Uh oh.... 呃哦

I believe your return statement in the toString method should be return "Dog's name: " + this.name; 我相信您在toString方法中的return语句应为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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM