Gaurav Gupta
Gaurav Gupta

Reputation: 4691

Why overriden toString() is not called in javascript

I tried to override the toString() but i found that, overridden function in not getting called at all.

I have gone through this and this, but i am not able to track my mistake.

My attempt:

DIRECTION = {
    NONE : 0,
    DIAGONAL: 1,
    UP: 2,
    LEFT: 3
};

var Node  = function () {
    this.direction =  DIRECTION.NONE;
    this.weight = 0;
};
Node.prototype.toString = function NodeToSting(){
    console.log('Is called');
    var ret = "this.weight";
    return ret;
};

(function driver(){
    var node1 = new Node();
    console.log(node1);
    //findLcs("ABCBDAB", "BDCABA");
})();

Output:

{ direction: 0, weight: 0 }

Upvotes: 3

Views: 459

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

console.log outputs the literal value to the console - it will not coerce your object to a string and therefore won't execute your toString implementation.

You can force it to output a string like this:

console.log(""+node1);

Example:

DIRECTION = {
    NONE : 0,
    DIAGONAL: 1,
    UP: 2,
    LEFT: 3
};

var Node  = function () {
    this.direction =  DIRECTION.NONE;
    this.weight = 0;
};
Node.prototype.toString = function NodeToSting(){
    console.log('Is called');
    var ret = "this.weight";
    return ret;
};

(function driver(){
    var node1 = new Node();
    alert(""+node1);
    //findLcs("ABCBDAB", "BDCABA");
})();

Upvotes: 7

Related Questions