最新消息:

Object,Array,String常用的原型方法总结

javascript feifei 2533浏览

Object.prototpye.toString

 

首先看一段ECMA中对Object.prototype.toString的解释:

Object.prototype.toString( )
When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
3. Return Result (2)

我们知道,Javascript中,一切皆为对象。所以如下代码,应当会输出对应字符:

标准浏览器中完美的作到,但是(为什么要说但是呢)IE6中,却会出现以下问题:

通过Object.prototype.toString.call获取的 字符串,undefined,null均为Object 

—————————————————————————————————————————————

Object.prototype.hasOwnProperty

在循环对象的过程中,使用hasOwnProperty()方法来检验是对象本身的属性还是原型链上的属性很重要

看看下面的这个例子

在这个例子中,我们有一个简单的称作man的对象字面量。在其他man定义之前或之后的地方,对象原型有一个很有用的clone()方法。因为原型链的原因,所有的对象都自动获得了这个方法。为了在枚举man对象的时候出现clone方法,你需要使用hasOwnProperty方法来区别。如果没有区别来自原型链的方法,那么就会有一些意想不到的事情发生:

另外一种使用方法如下:

这样写的好处是可以防止man重新定义了hasOwnProperty方法导致的冲突。如果不想写这么长的一串,你也可以这样:

———————————————————————————————————————————

Array.prototype.push

常用语数组拼接,对比和数组的concat方法的区别

往一个数组中添加另外另外一个数组中的元素,两种方式比较(拼接和push)

这个做法依赖两点:
1、apply方法的第二个参数是数组的情况下,这个数组参数会作为apply的方法的参数列表(arguments);
2、push方法接受可变参数列表:array.push(item1 [, item2 … [, itemN]])
按照源码注释的说法,“super-fast way to populate an object with array-like properties”

同样也可以使用数组的默认concat方法,例如:

结论:Array.prototype.push 速度会比 concat快一些

————————————————————————————————————————————————

Array.prototype.slice

1.两个部分,一个是String.slice()

slice( ) returns a string containing a slice, or substring, of string. It does not modify string。
slice()返回一个子片段,对原先的string没有影响,还可以用负数当参数。
Example:

 

2.Array.slice(start,end)

slice( ) returns a slice, or subarray, of array. The returned array contains the element specified by start and all subsequent elements up to, but not including, the element specified by end. If end is not specified, the returned array contains all elements from the start to the end of array.
返回从start开始到end的子数组,如果end这个参数没有被设置,则返回从start开始到最后的数组元素。
Example:

除了正常用法,slice 经常用来将 array-like 对象转换为 true array。在一些框架中会经常有这种用法。

call的作用是改变this的指向,就相当于arguments调用了,slice这个方法。0就是start=0,end没指定,所以返回整个arguments,这个时候就转换成数组了。

读后感: 能用slice方法的,只要有length属性就行。虽然arguments有length属性,但是没有slice方法,所以呢,Array.prototype.slice()执行的时候,Array.prototype已经被call改成arguments了,因为满足slice执行的条件(有length属性),所以没有报错。感觉有点hack的意思了。

其他介绍说明:http://hi.baidu.com/elmo07/item/f59bdb17bde652f8746a8447

—————————————————————————————————————————-

 

转载请注明:飞飞的个人网站 » Object,Array,String常用的原型方法总结