简体   繁体   中英

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. When I run this, obj.toString is called over and over until I receive a 'Maximum call stack size error'. However, if I replace 'this' in the obj.type return to 'this.name', everything works fine. I realize I wouldn't normally return just 'this', but why is it getting caught in a loop when I do?

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.

In this case, you have a custom toString() function. 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; .

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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