js中toString 和 object.toString区别解释,
js中toString 和 object.toString区别解释,
1.toString 和 object.toString运行结果演示
var str = 'this is string';
alert(str.toString());
运行结果:
var str = 'this is string';
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方法,我们可以通过实验看看有没有达到我们想要的结果。
var str = 'this is string';
alert(toString.call(str));
运行结果
var str = 'this is string';
alert(toString.apply(str));
运行结果:
这的确是我们想要的结果,大家可以试试其他的类型
4.注意的地方
在IE中使用toString.call()方法时会报错,建议使用Object.prototype.toString.call()(所有浏览器都支持),这是js为原始对象原型提供的toString方法,用法和toString方法一样。
相关文章
- 暂无相关文章
用户点评