函數對象 Function Object
函數就是對象。對象字面量產生的對象連結到Object.prototype。函數對象連結到Function.prototype。每個函數在建立時附有兩個附件的隱藏屬性:函數的上下文和實現函數行為的代碼。
函數字面量 Function Literal
函數對象可以通過函數字面量來建立。
var add = function(a, b){return a+b;};
調用 Invocation
除了聲明時定義的形式參數,每個函數接收兩個附加的參數:this 和arguments。
this在物件導向編程中非常重要,它的值取決於調用的模式。在JS中,一共有四種調用模式,這些模式在初始化參數this上存在差異。
1、方法調用模式
2、函數調用模式
3、構造器調用模式
4、apply調用模式
方法調用模式 The Mehtod Invocation Pattern
當一個函數被儲存為一個對象的屬性並且被調用時,this綁定到該對象。
通過this可取得他們所屬對象的內容相關的方法稱為公用方法。
var myObject = {
value : 0,
increment:function(inc)
{
this.value += (inc);
}
};
myObject.increment(3);
myObject.increment(3);
alert(myObject.value);//result is 6.
函數調用模式 The Function Invocation Pattern
在函數調用模式下,this被綁定到全域對象上。這個是javascript語言設計上的一個錯誤。
看如下code:
var g='globle';
var o=function()
{
var g= 'self';
alert(this.g);
}();
//result is 'globle'. it is not correct.
可以採用以下方法避免
var g='globle';
var o=function()
{
var that = this;
that.g='self';
alert(this.g);
}();
//result is 'self', it is correct.
構造器調用模式 The Consultant Invocation Pattern
js是居於原型繼承的語言,所以對象可以從其他對象直接繼承屬性。該語言是無類別的。
如果一個函數前面帶上new來調用,那麼將建立一個隱藏連結到該函數的prototype成員的新對象,同時this將會被綁定到那個新對象上。
不推薦使用這種方法。
var Quo=function(string)
{
this.status =string;
};
Quo.prototype.get_status = function(){return this.status;};
var myQuo = new Quo("Confused");
alert(myQuo.get_status());
//new could not be lost.
Apply調用模式 The Apply Invocation Pattern
通過apply/call方法調用函數,其中第一個參數為我們指定的this的值。
var statusObject = {status : 'A-OK'};
var status = Quo.prototype.get_status.apply(statusObject);
//result is 'A-OK';the first param is "this" value.