function Fun (name,age) {
this.name=name;
this.age=age;
}
var fun2= new Fun("tom",17);
console.log(fun2) //Fun {name: "tom", age: 17}
以下代码块中 console.log(fun2.toString)
function Fun (name,age) {
this.name=name;
this.age=age;
}
var fun2= new Fun("tom",17);
console.log(fun2.toString) //[object Object]
检查两个代码块打印的东西是否相等,结果返回ture,
console.log(fun2.toString()==fun2);
所以,当在页面中直接打印一个对象时,实际上是打印该对象的toString()方法的返回值;而toString()来自于Object原型对象,
console.log(fun2.__proto__.hasOwnProperty("toString")); //false
console.log(fun2.__proto__.__proto__.hasOwnProperty("toString")); //ture,
即toString()方法在原型的原型里,可以修改原型对象的返回值。
function Fun (name,age) {
this.name=name;
this.age=age;
}
var fun2= new Fun("tom",17);
//直接给toString方法修改一个返回值
fun2.toString=function () {
return "我是被修改的toString()方法的返回值"
}
console.log(fun2.toString());
给多个实例修改toString,即修改Fun原型的toString:
function Fun (name,age) {
this.name=name;
this.age=age;
}
var fun2= new Fun("tom",17);
var fun3= new Fun("marry",12);
Fun.prototype.toString=function(){
return "Fun[name="+this.name+",age="+this.age+"]"
}
// console.log(fun2.toString()==fun2);
console.log(fun2);
console.log(fun2.toString());//Fun {name: "tom", age: 17}
console.log(fun3);
console.log(fun3.toString());//Fun[name=marry,age=12]