call()可以改变函数中this的指向,这里举一个例子:
//创建一个伪数组obj(和数组类似具有length属性,但是不具有数组的方法)
var obj = {
0:10,
1:100,
2:200,
3:300,
length:4
}
//如果要模拟数组的方式添加新的元素(对象)
obj['4'] = 400;
obj.length ++;
var obj = {
0:10,
1:100,
2:200,
3:300,
length:4
}
//但是借用call我们可以借用数组原型的方法
Array.prototype.push.call(obj,30);
console.dir(obj);//{0: 10, 1: 100, 2: 200, 3: 300, 4: 400, length: 5}
//还可以使用数组其他方法如splice
Array.prototype.splice.call(obj,0,3);
console.dir(obj);//{0: 300, 1: 400, length: 2}