为什么在JavaScript中重写的toString()方法没有被调用

3

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

我已经阅读了这个这个,但我无法追踪我的错误。

我的尝试:

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 }

2
它应该在哪里调用呢?console.log不会输出。 - elclanrs
1
调用 toString 的位置在哪里? - Jonathan
1个回答

7

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


@SunilD。没错,但我不想在SO代码片段中放置console.log,因为这并不明显。 - CodingIntrigue

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接