Javascript 如何创建对象的自定义toString方法
我想创建以下Javascript 如何创建对象的自定义toString方法,javascript,Javascript,我想创建以下对象的自定义toString()方法。但我不能这样做。我读了我应该重写prototype.toString,但是我得到了编译错误 var a = { someProperty: 1, someotherProperty:3 } a.prototype.toString = function customPrint(){ return "the custom print is "+(someProperty+someotherProperty); } va
对象的自定义toString()
方法。但我不能这样做。我读了我应该重写prototype.toString
,但是我得到了编译错误
var a = {
someProperty: 1,
someotherProperty:3
}
a.prototype.toString = function customPrint(){
return "the custom print is "+(someProperty+someotherProperty);
}
var b = {
somePropertyb: 2
}
function printObject(){
console.log("using , hello: a:",a,"b:",b); //prints using , hello: a: { someProperty: 1, someotherProperty: 3 } b: { somePropertyb: 2 }
console.log("using + hello: a:"+a+"b:"+b);//prints using + hello: a:[object Object]b:[object Object] if I remove a.prototype.toString code
}
printObject()
我得到的错误是
node print.js
print.js:6
a.prototype.toString=函数customPrint(){
^
TypeError:无法设置未定义的属性“toString”
at Object.(C:\…\print.js:6:22)
a
不是一个类,因此它没有一个原型
,您可以这样分配。相反,只需将toString
方法放在对象本身上:
var a={
某些属性:1,
其他属性:3,
toString:function(){
返回“自定义打印为”+this.someProperty+this.someotherProperty;
},
}
变量b={
某些属性b:2
}
函数printObject(){
log(“使用+hello:a:+a+”b:+b”);
}
printObject()