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:
console.log(spot.toString())
return "Dog's name: " + this.type();
return this;
// Hmmmm. How do we add "this" to our string. Easy we call toString().
return "Dog's name: " + this.type();
return this;
// Hmmmm. How do we add "this" to our string. Easy we call toString().
return "Dog's name: " + this.type();
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.