一、概念
Function(函數(shù))類型實(shí)際上是對(duì)象。每個(gè)函數(shù)都是 Function 類型的 實(shí)例,而且都與其他引用類型一樣具有屬性和方法。由于函數(shù)是對(duì)象,因此函數(shù)名實(shí)際上也 是一個(gè)指向函數(shù)對(duì)象的指針
二、作為值的函數(shù)
ECMAScript 中的函數(shù)名本身就是變量,所以函數(shù)也可以作為值來使用。也就是說,不 僅可以像傳遞參數(shù)一樣把一個(gè)函數(shù)傳遞給另一個(gè)函數(shù),而且可以將一個(gè)函數(shù)作為另一個(gè)函數(shù) 的結(jié)果返回。
function box(sumFunction, num){
return sumFunction(num);
}
function sum(num) {
returnnum+10;
}
varresult=box(sum,10);
三、函數(shù)內(nèi)部屬性
- arguments
function box(num){
if(num<=1){
return 1;
}
else{
return num*arguments.callee(num-1);//使用 callee 來執(zhí)行自身 等同于returnnum*box(num-1);
}
}
- this
window.color='紅色的'; //全局的 或者寫成var color = '紅色的'
alert(this.color); //打印全局的 color
var box={
color:'藍(lán)色的', //局部的 color
sayColor :function(){
alert(this.color); //此時(shí)的 this 只能 box 里的 color
}
};
box.sayColor(); //打印局部的 color
alert(this.color); //還是全局的
四、函數(shù)屬性和方法
- length 屬性表示函數(shù)希望接收的命名參數(shù)的個(gè)數(shù)
functionbox(name,age){
alert(name+age);
}
alert(box.length);
-
prototype 屬性 (原型)
為一個(gè)特定類聲明通用的變量或者函數(shù)。function Test(){ } alert(Test.prototype); // 輸出 "Object" 用prototype給對(duì)象 添加屬性
function Fish(name, color){
this.name=name;
this.color=color;
}
Fish.prototype.livesIn="water";
Fish.prototype.price=20;
- 用prototype給對(duì)象添加函數(shù)
function Employee(name, salary)
{
this.name=name;
this.salary=salary;
}
Employee.prototype.getSalary=function getSalaryFunction()
{
return this.salary;
}
Employee.prototype.addSalary=function addSalaryFunction(addition)
{
this.salary=this.salary+addition;
}
-
每個(gè)函數(shù)都 包含這兩個(gè)非繼承而來的方法。apply()和 call()
var color='紅色的'; //或者 window.color='紅色的';
var box={
color:'藍(lán)色的'
};
function sayColor(){
alert(this.color);
}
sayColor(); //作用域在 window
sayColor.call(this); //作用域在 window
sayColor.call(window); //作用域在 window
sayColor.call(box); //作用域在 box,對(duì)象冒充
注:
使用 call()或者 apply()來擴(kuò)充作用域的最大好處,
就是對(duì)象不需要與方法發(fā)生任何耦合 關(guān)系(耦合,
就是互相關(guān)聯(lián)的意思,
擴(kuò)展和維護(hù)會(huì)發(fā)生連鎖反應(yīng))。
也就是說,
box 對(duì)象和 sayColor()方法之間不會(huì)有多余的關(guān)聯(lián)操作,
比如 box.sayColor=sayColor;