我想创建以下toString()
对象的自定义a
方法。但我无法这样做。我读过我应该覆盖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 = function customPrint(){
^
TypeError: Cannot set property 'toString' of undefined
at Object.<anonymous> (C:\...\print.js:6:22)
答案 0 :(得分:7)
a
不是一个类,因此没有prototype
可以分配给它。相反,只需将toString
方法放在对象本身上:
var a = {
someProperty: 1,
someotherProperty: 3,
toString: function() {
return "the custom print is " + this.someProperty + this.someotherProperty;
},
}
var b = {
somePropertyb: 2
}
function printObject() {
console.log("using + hello: a:" + a + "b:" + b);
}
printObject()