---
title: "javascript回函数的几种调用方法"
author: "biyeah"
date: "2011-12-22T04:39:24Z"
tags: []
categories: ["编程语言"]
slug: "javascript"
draft: false
lastmod: "2011-12-22T04:39:59Z"
id: 1320159
url: "https://biyeah.iteye.com/blog/1320159"
---

先来看下基本的知识，对于一个函数的调用，方法有以下几种。


```javascript
//下面的几种写法是等价的。
alert('something');
this.alert('something');
alert.call(this,'something');
alert.apply(this,['something']);
```


以实现数组中each的方法做为例子。
第一种方式：

```javascript
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
```


第二种方式：

```javascript
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
```


第三种方式：

```javascript
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
```