javascript 中记录对象时如何强制使用 toString

How to force toString when logging object in javascript

我想知道是否可以从这段代码中得到 "content here" 作为响应(例如日志):

function Obj () {
    this.toString = function(){ return "content here" };
}
var obj = new Obj;
console.log(obj);

我知道我可以用 String()、toString() 和 ""+obj 强制它,但我想知道是否有一种方法可以从对象内部强制它。

您的编辑添加

I know I can force it with String(), toString() and ""+obj, but I want to know if there is a way of forcing it from WITHIN the object.

...更改问题。简单的答案是 "no, you can't do that within the object." 为了调用对象上的 toString,需要说 "I want the primitive form of this"(或特别是 "I want the string form of this")。 console.log 不会那样做,它提供的信息比那更丰富。

你在你的对象上放置一个 toString 意味着任何时候它被转换为一个字符串,你的函数都会被调用,但它并没有规定什么时候发生。您也可以使用 valueOf。规范中有更多相关内容:§9.1 - ToPrimitive, §8.12.8 - [[DefaultValue]] (hint), and §9.8 - ToString.

但是添加 toString(或 valueOf)不会让您决定它何时发生;你不能,这只是由 JavaScript 的规则或执行它的调用代码(显式或隐式)完成的。


原答案:

最简单的方法就是用String就可以了:

console.log(String(obj));

您可以添加自己的方法:

console.logString = function(s) {
    console.log(String(s));
};

可以可能改变log:

var old = console.log;
console.log = function(s) {
    var a = Array.prototype.map.call(arguments, function(a) {
        return String(a);
    };
    return old.apply(console, a);
};

...但是我不推荐它