先来看下基本的知识,对于一个函数的调用,方法有以下几种。
以实现数组中each的方法做为例子。
第一种方式:
第二种方式:
第三种方式:
//下面的几种写法是等价的。
alert('something');
this.alert('something');
alert.call(this,'something');
alert.apply(this,['something']);
以实现数组中each的方法做为例子。
第一种方式:
Array.prototype.each = function(callback){
for(var i = 0; i< this.length;i++){
callback(this[i]);//参数既为函数名,直接加括号调用。
}
}
[1,2,3,4].each(alert);//ok
[1,2,3,4].each(console.log);//chrome下不能运行,而在FF中可以运行
[1,2,3,4].each(function(x){
console.log(x);
});//ok
第二种方式:
Array.prototype.each = function(callback){
for(var i = 0; i< this.length;i++){
callback.call(this,this[i]);//使用call
}
}
[1,2,3,4].each(alert);//在chrome和FF不能运行。
[1,2,3,4].each(console.log);//chrome下不能运行,而在FF中可以运行
[1,2,3,4].each(function(x){
console.log(x);
});//ok
第三种方式:
Array.prototype.each = function(callback){
for(var i = 0; i< this.length;i++){
callback.apply(this,[this[i]]);//使用apply
}
}
[1,2,3,4].each(alert);//在chrome和FF不能运行。
[1,2,3,4].each(console.log);//chrome下不能运行,而在FF中可以运行
[1,2,3,4].each(function(x){
console.log(x);
});//ok