toString 哪里不起作用?
function dTree() {
return {
init : function(data) {
this.data = data;
},
node : function(i){
return '' + i;
}
}
};
dTree.prototype.toString = function() {
var str = '';
for(var i = 0; i < this.data.length; i++)
{
str += this.node(this.data[i]);
};
return str;
}
dTree1 = new dTree();
dTree1.init([1,2,3]);
alert(dTree1+'')
我期望它输出 123
如何正确地做到这一点?
function dTree() {
return {
init : function(data) {
this.data = data;
},
node : function(i){
return '' + i;
}
}
};
dTree.prototype.toString = function() {
var str = '';
for(var i = 0; i < this.data.length; i++)
{
str += this.node(this.data[i]);
};
return str;
}
dTree1 = new dTree();
dTree1.init([1,2,3]);
alert(dTree1+'')
I'm expecting it to output 123
How to do it the right way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是创建构造函数的方式。构造函数不返回任何内容,它们操作
this
对象:您也可以将
toString
的定义粘贴到构造函数中,除非您正在用它做一些特殊的事情:That's not how you make constructors. Constructors don't return anything, they manipulate the
this
object:You could also stick the definition of
toString
into the constructor as well, unless you're doing something special with it:您将从构造函数返回一个普通的新对象,构造函数中的 this 对象根本没有被使用,并且该对象是分配了正确原型对象的对象。
You are returning a plain new object from your constructor, the
this
object inside your constructor is not used at all, and that object is the one that has the right prototype object assigned.