JS中的toString问题
一 Object.prototype中的toString()方法
因为JS中所有数据类型都是Object,而Oeject.prototype中被写入了toString()方法,因此万物都可以通过原型链找到这个方法。
//通过call函数取调用 Object.prototype对象的toString方法
var a = Object.prototype.toString
console.log(a.call(2));
console.log(a.call(true));
console.log(a.call('str'));
console.log(a.call([]));
console.log(a.call(function () { }));
console.log(a.call({}));
console.log(a.call(undefined));
console.log(a.call(null));
二 被改写的toString()
可以注意到,Object.prototype对象中的toString方法只能返回类型。
JS的作者考虑到了这个问题,因此在Number.prototype、Function.prototype和Arrary.prototype对象中重写了这个方法。
console.log((2).toString());
console.log([1,2,3].toString());
console.log((function test(){ var lzc = "加油"}).toString());
三 自己重写toString()
我们通过构造函数构造对象的时候,可以自己在构造函数的prototype中重写toString方法
- 这是没有重写的
//这是没有被重写时候的
var Person =function(name,height,weight) {
this.name = name
this.height=height
this.weight=weight
}
lzc =new Person('lzc','175','65KG')
console.log(lzc.toString());
原型链方位原理:lzc对象>Person.prototype>Object.prototype
最终在Object.prototype中找到了toString方法
- 这是重写之后的
var Person =function(name,height,weight) {
this.name = name
this.height=height
this.weight=weight
}
//自己重写
Person.prototype.toString = function(){
return "Person{name:"+this.name+",height:"+this.height+",weight"+this.weight+"}"
}
lzc =new Person('lzc','175','65KG')
console.log(lzc.toString());
原型链方位原理:lzc对象>Person.prototype
最终在Person.prototype中找到了toString方法,便停止继续查找