我试图覆盖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 }
答案 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");
})();