[英]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: 因此,让我们跟踪一下:
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;
我相信您在
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.