## 一、函數聲明
a. 普通方式
~~~
function box(參數){
......
}
~~~
b. 變量方式
~~~
var box = function(參數){
......
}
~~~
c. function構造方法(不推薦)
~~~
var box = new Function('變量1','變量2','函數體');
~~~
由此可以看出,函數是對象,函數名是對象的指針
## 二、函數調用
`box();`
調用的時候可以執行2種操作:
1. `alert();`
2. 返回`return`
3. **作為值的函數**,函數可以作為參數傳遞給另一個函數
~~~
//函數作為 返回值 傳遞
function box(a,b){
return a+b;
}
function sum(c){
return c+10;
}
box(sum(20),50);
~~~
~~~
//函數作為 值 傳遞
function box(a,b){
return a(b);
}
function a(sum){
return sum+100;
}
var result = box(sum,10);
~~~
## 三、 函數內部屬性
### 1. arguments
主要用來保存參數
注:參數以數組的形式存在arguments中,因此
`arguments.length` 參數長度
`arguments[0]` 獲取某個參數
`arguments.callee` 獲取自身函數名,遞歸函數內部會調用自身
~~~
function box(num){
if(num<1){
return 1;
}else{
return arguments.callee(num-1)*num; //return box(num-1)*num;
}
}
~~~
### 2.this
this 代表外面 "函數" 所處的作用域 對象,最高的作用域的是window
~~~
window.color='紅色';
function say(){
alert(this.color);
}
say();
~~~
~~~
var box={
color:'red'
}
function say(){
alert(this.color);
}
box.say=say;
box.say();
~~~
## 四、函數屬性和方法
函數是對象的一種,因此有對應的屬性和方法
### 函數屬性
`arguments.length`
~~~
//獲取函數參數的個數
function box(a,b,c){}
alert(box.length);
~~~
### 函數方法
prototype原型方法
apply,call作用是設置函數內部this的值,在一個函數里面調用別的函數
這2個方法主要作用是改變作用域
#### apply() 參數是數組
~~~
//原函數
function box(a,b){
return a+b;
}
//用另一個函數調用這個函數,
function add(c,d){
//add冒充box函數的相加功能
return box.repply(this,[c,d]); //此時的this表示window下面的box
//下面寫起來更方便
//rerurn bxo.repply(this,arguments);
}
//運行
add(5,10);
~~~
~~~
box.repply(this,arguments);
~~~
#### call() 參數一個一個傳遞
~~~
//方式一,有參數
box.call(this,n1,n2);
~~~
~~~
//方式二,無參數
box.call(作用域);
~~~
//改變作用域的例子,對象和方法無需任何耦合關系
~~~
var color='#000';
var box={
color:'#333'
}
function say(){
alert(this.color);
}
say.call(window);
say.call(this);
say.call(box);
~~~
