为什么不在javascript中调用覆盖toString()

时间:2015-07-02 07:36:30

标签: javascript node.js tostring override

我试图覆盖toString(),但我发现,被覆盖的函数根本没有被调用。

我经历了thisthis,但我无法追踪我的错误。

我的尝试:

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");
})();

输出:

{ direction: 0, weight: 0 }

1 个答案:

答案 0 :(得分:6)

console.log将字面值输出到控制台 - 它不会将您的对象强制转换为字符串,因此无法执行toString实施。

您可以强制它输出如下字符串:

console.log(""+node1);

示例:



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");
})();