function Person(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
}
//修改原型的toString,能打印person的所有对象
Person.prototype.toString=function(){
return “Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]”;
};
var per = new Person("孙悟空",18,"男");
var per2 = new Person("猪八戒",28,"男");
//当我们直接在页面中打印一个对象时,事件上是输出的对象的toString()方法的返回值
//如果我们希望在输出对象时不输出[object Object],可以为对象添加一个toString()方法
//打印Person[name=孙悟空,age=18,gender=男]
per.toString = function(){
return “Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]”;
}//这种方式只修改一个对象
console.log(per.toString());
console.log(per2);
JavaScript---toString()
于 2022-03-29 10:57:24 首次发布