javascript回函数的几种调用方法
先来看下基本的知识,对于一个函数的调用,方法有以下几种。
//下面的几种写法是等价的。alert('something');this.alert('something');alert.call(this,'something');alert.apply(this,['something']);
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