Gau*_*pta 2 javascript overriding tostring node.js
我试图覆盖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");
})();
Run Code Online (Sandbox Code Playgroud)
输出:
{ direction: 0, weight: 0 }
Run Code Online (Sandbox Code Playgroud)
console.log将文字值输出到控制台 - 它不会将您的对象强制转换为字符串,因此不会执行您的toString实现.
您可以强制它输出如下字符串:
console.log(""+node1);
Run Code Online (Sandbox Code Playgroud)
例:
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");
})();Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
316 次 |
| 最近记录: |