为什么在 javascript 中不调用覆盖 toString()
Why overriden toString() is not called in javascript
我试图覆盖 toString() 但我发现,覆盖的函数根本没有被调用。
我已经完成了 this and this,但我无法追踪我的错误。
我的尝试:
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 }
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");
})();
我试图覆盖 toString() 但我发现,覆盖的函数根本没有被调用。
我已经完成了 this and this,但我无法追踪我的错误。
我的尝试:
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 }
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");
})();