user198729
user198729

Reputation: 63646

Where toString fails to work?

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?

Upvotes: 0

Views: 259

Answers (2)

Sasha Chedygov
Sasha Chedygov

Reputation: 130817

That's not how you make constructors. Constructors don't return anything, they manipulate the this object:

function dTree() {
    this.init = function(data) {
        this.data = data;
    };
    this.node = function(i){
        return '' + i;
    };
}

You could also stick the definition of toString into the constructor as well, unless you're doing something special with it:

function dTree() {
    this.init = function(data) {
        this.data = data;
    };
    this.node = function(i) {
        return '' + i;
    };
    this.toString = function() {
        var str = '';
        for(var i = 0; i < this.data.length; i++)
        {
            str += this.node(this.data[i]);
        };
        return str;
    };
}

Upvotes: 4

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827416

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.

function dTree() {
  this.init = function(data) {
    this.data = data;
  };
  this.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 + '');

Upvotes: 2

Related Questions