views:

51

answers:

2
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?

+4  A: 

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;
    };
}
musicfreak
+2  A: 

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 + '');
CMS