我正在尝试为对象创建自定义打印。我注意到在console.log中使用+
使用对象的toString
。默认toString
会返回[object Object]
。我还注意到使用,
只是打印所有属性及其值。在console.log中使用逗号时,是否可能调用我的自定义print(toString)?
var a = {
someAProperty: 1,
toString: function() {
return "the custom print is " + this.someAProperty;
}
}
var b = {
someBProperty: 2
}
class C {
constructor(someCProperty){
this.someCProperty=someCProperty;
};
}
C.prototype.toString = function customPrint(){
return "someCProperty is "+this.someCProperty;
}
class D {
constructor(someDProperty){
this.someDProperty=someDProperty;
};
}
function printObject(){
console.log("\nusing , \n a:( object with toString property)",a,"\nb (object without toString):",b,"\nc (class with toString):",new C(1),"\nd (class without toString) ", new D(4));
console.log("\nusing + \n a:( object with toString property)"+a+"\nb (object without toString):"+b+"\nc (class with toString):"+new C(1)+"\nd (class without toString) "+ new D(4));
}
printObject()
要运行上述代码,我使用了node.js
node print.js
using ,
a:( object with toString property) { someAProperty: 1, toString: [Function: toString] }
b (object without toString): { someBProperty: 2 }
c (class with toString): C { someCProperty: 1 }
d (class without toString) D { someDProperty: 4 }
using +
a:( object with toString property)the custom print is 1
b (object without toString):[object Object]
c (class with toString):someCProperty is 1
d (class without toString) [object Object]
在console.log
中使用逗号时,是否可以获得以下输出?即console.log("\nusing , \n a:( object with toString property)",a,"\nb (object without toString):",b,"\nc (class with toString):",new C(1),"\nd (class without toString) ", new D(4));
a:( object with toString property)the custom print is 1
b (object without toString):[object Object]
c (class with toString):someCProperty is 1
d (class without toString) [object Object]
答案 0 :(得分:0)
明确致电.toString()
:
console.log("\nusing , \n a:( object with toString property)", a.toString(),
"\nb (object without toString):", b.toString(),
"\nc (class with toString):", (new C(1)).toString(),
"\nd (class without toString) ", (new D(4)).toString());
答案 1 :(得分:0)
console.log
接受可变数量的参数并输出它们。在您的示例中使用+
时,您正在执行"some string" + object
,因此+
最终成为字符串连接(与console.log
无关),结果字符串为作为单个参数传递给console.log
。当你使用逗号时,你将两个不同的参数传递给console.log
,它以自己的方式处理每个参数。
您可以在对象上包含任何内容,除非您强制使用toString
,否则会导致其+
被调用(例如,使用String(yourObject)
或inspect
),但某些控制台(例如Node.js中的控制台)如果在您的对象上,则会使用名为const util = require('util');
var obj = {
answer: 42
};
console.log("Without inspect", obj);
obj[util.inspect.custom] = function() {
return "The answer is " + this.answer;
};
console.log("With inspect", obj);
的函数:
console.log
否则,只需确保在调用{{1}}时强制转换为字符串(可能通过使用包装函数而不是直接调用它)。