JS中的toString问题

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方法,便停止继续查找

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值