如何创建对象的自定义toString方法

时间:2018-04-30 08:12:49

标签: javascript

我想创建以下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)

1 个答案:

答案 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()