js中toString 和 object.toString区别解释

1.toString 和 object.toString运行结果演示

 

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var str = 'this is string';  
  2. alert(str.toString());  

运行结果:



[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var str = 'this is string';  
  2. alert(toString(str));  
运行结果:


所以从上述运行结果得知object.toString()只是输出该对象的信息,并以字符表示,和许多其他的语言诸如Java的object.toString()一样,但是js提供的内置函数toString()输出的结果为"[object Window]",这和str对象没人任何联系,接下来我只对toString()方法详解。


2.toString()详解

ECMA 5.1 中关于该方法的描述是这样的:

When the toString method is called, the following steps are taken:
If the this value is undefined, return “[object Undefined]“.
If the this value is null, return “[object Null]“.
Let O be the result of calling ToObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings “[object ", class, and "]“.翻译如下:

当调用toString方法时,下列步骤会被执行:

    如果this未定义时,返回“[object Undefined]”

         如果this为null时,返回“[object Null]”

    定义O,并且让O=ToObject(this)

    定义class,并且使class为O内置属性[[class]]的值

    返回三个字符串的拼接字符:"[object",class,"]"


通过官方解释,可以清晰的得出toString()是在以特殊的字符串形式输出this的类型,不管你传入什么参数,该方法都是执行了window.toString()方法,this一直指向了window对象,所以输出了上述结果。


3.怎么使用toString()方法判断任意类型

通过上面对toString的讲解可知,toString()始终判断的是this的类型,那么只要将this指向其他对象,就能判断该对象的类型。

到了这步就比较清楚了,js中改变this有那种方式,一种是call方法,另一种是apply方法,我们可以通过实验看看有没有达到我们想要的结果。

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var str = 'this is string';  
  2. alert(toString.call(str));  
运行结果


[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var str = 'this is string';  
  2. alert(toString.apply(str));  
运行结果:


这的确是我们想要的结果,大家可以试试其他的类型


4.注意的地方

在IE中使用toString.call()方法时会报错,建议使用Object.prototype.toString.call()(所有浏览器都支持),这是js为原始对象原型提供的toString方法,用法和toString方法一样。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值