继承本地对象:
本地对象是可以被继承的,如Array.prototype保存着全部的Array实例的方法。
如果想在自定义对象(假设为myArray)中访问这些方法,办法就是myArray.__proto__ == Array.prototype.
如果只使用Array中的部分功能,那就没必要继承Array
只需借用其中的函数即可。
ES-5中对Array.prototype.join的描述:
它不检测对象类型, All it does is a joining loop over properties with indicies 0..length-1。(换句话说对象要有length属性,属性key需从0开始到length-1)
Array的方法常被用于类数组对象的操作
本地对象是可以被继承的,如Array.prototype保存着全部的Array实例的方法。
如果想在自定义对象(假设为myArray)中访问这些方法,办法就是myArray.__proto__ == Array.prototype.
来看例子:
// constructor
function MyArray() {
this.stringify = function() {
return this.join(', ')
}
}
// Make sure that (new MyArray) has the right __proto__
MyArray.prototype = Array.prototype
// Test
var myArr = new MyArray()
myArr.push(1)
myArr.push(2)
alert( myArr.stringify() ) // 1, 2
alert( myArr.length ) // 2 in all except IE //这里myArray已经具有了Array的所有方法
方法借用:
如果只使用Array中的部分功能,那就没必要继承Array
只需借用其中的函数即可。
var join = Array.prototype.join
// same but shorter
var join = [].join
var obj = {
0: 'first',
1: 'second',
length: 2
}
alert( [].join.call(obj, ', ') ) // first, second
ES-5中对Array.prototype.join的描述:
它不检测对象类型, All it does is a joining loop over properties with indicies 0..length-1。(换句话说对象要有length属性,属性key需从0开始到length-1)
Array的方法常被用于类数组对象的操作