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]
檢查兩個(gè)代碼塊打印的東西是否相等训唱,結(jié)果返回ture,
console.log(fun2.toString()==fun2);
所以,當(dāng)在頁(yè)面中直接打印一個(gè)對(duì)象時(shí)奠宜,實(shí)際上是打印該對(duì)象的toString()方法的返回值菱鸥;而toString()來自于Object原型對(duì)象盯串,
console.log(fun2.__proto__.hasOwnProperty("toString")); //false
console.log(fun2.__proto__.__proto__.hasOwnProperty("toString")); //ture,
即toString()方法在原型的原型里娇唯,可以修改原型對(duì)象的返回值齐遵。
function Fun (name,age) {
this.name=name;
this.age=age;
}
var fun2= new Fun("tom",17);
//直接給toString方法修改一個(gè)返回值
fun2.toString=function () {
return "我是被修改的toString()方法的返回值"
}
console.log(fun2.toString());
給多個(gè)實(shí)例修改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]