所以我有这个超级简单的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());
答案 0 :(得分:1)
在javascript中对对象进行字符串化时,会调用toString()函数。
在这种情况下,您有一个自定义toString()函数。凉。
所以让我们追踪一下:
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;
哦,哦......
答案 1 :(得分:0)
我相信toString
方法中的退货声明应为return "Dog's name: " + this.name;
。
答案 2 :(得分:-1)
obj.SetValue(ForecastPoint.ValueProperty, value)