1.函數(shù)對象
函數(shù)就是對象蔼囊。
對象是“名\值”對的集合并擁有一個連接到對象原型的隱藏的連接
函數(shù)對象連接到Function.prototype上
每個函數(shù)對象在創(chuàng)建時,隱藏兩個屬性州弟,即函數(shù)的上下文和實(shí)現(xiàn)函數(shù)行為的代碼
每個函數(shù)在創(chuàng)建時都會攜帶一個prototype屬性仍律,它的值擁有一個constructor屬性且值為該對象的函數(shù)
2.函數(shù)字面量
函數(shù)字面量 = function關(guān)鍵字 + 函數(shù)名(這里省略) + 參數(shù)(a, b) + body函數(shù)體
var add = function (a, b) {
return a + b;
}
alert(add(3, 4)); // 7
3.調(diào)用
調(diào)用一個函數(shù)即暫停當(dāng)前函數(shù)并把執(zhí)行權(quán)交給新函數(shù)嘿悬。
調(diào)用的函數(shù)除了接受實(shí)參外,還將接受this和arguments兩個參數(shù)
this的值取決于調(diào)用的模式:方法調(diào)用模式水泉、函數(shù)調(diào)用模式善涨、構(gòu)造器模式和apply調(diào)用模式
arguments表示接受實(shí)參的偽數(shù)組
方法調(diào)用模式
當(dāng)一個函數(shù)被保存為一個對象的屬性,我們將這個函數(shù)成為方法
當(dāng)這個方法被調(diào)用時草则,this被綁定到該對象
var myObject = {
value : 0,
increment : function (inc) {
alert(this); // [object Object],即myObject對象
this.value += typeof inc === "number" ? inc : 1;
}
}
myObject.increment();
document.writeln(myObject.value); // 1
myObject.increment(2);
document.writeln(myObject.value); // 3
當(dāng)一個函數(shù)被非對象調(diào)用時钢拧,那么它就是方法調(diào)用模式
this被綁定到window對象中
window.value = 1;
myObject.one = function () {
var helper = function () {
alert(this.value); // 1,這個匿名函數(shù)中的this統(tǒng)統(tǒng)指向window
this.value = add(this.value, this.value);
}
helper();
}
myObject.one();
document.writeln(myObject.value); // 3炕横,沒有變化
document.writeln(this.value); // 2源内,由add()方法已經(jīng)改變
解決方法:用that將this保留下來,即把執(zhí)行環(huán)境保存下來
myObject.two = function () {
var that = this; // 將this代表的myObject對象保存到that變量中
var helper = function () {
這是that就代表了myObject對象
that.value = add(that.value, that.value);
}
helper();
}
myObject.two();
document.writeln(myObject.value); // 6
document.writeln(this.value); // 1
構(gòu)造器調(diào)用模式
如果一個函數(shù)在其前面加new調(diào)用份殿,那么將創(chuàng)建一個連接到本函數(shù)的prototype成員的新對象
而this將會綁定到那個新對象中
var Que = function (string) {
this.name = string;
}
Que.prototype.getName = function () {
return this.name;
}
var q = new Que("no");
alert(q.getName()); // no
Apply調(diào)用模式
apply函數(shù)構(gòu)建一個數(shù)組并去其去調(diào)用函數(shù)
它接受兩個參數(shù):第一個是將被綁定this的值膜钓,第二個是一個數(shù)組
var array = [3, 4];
alert(add.apply(null, array)); // 7, this沒有被強(qiáng)制綁定值嗽交,即為window
var nameObject = {
name : "zhangfei"
}
// 將this綁定到nameObject中,并且調(diào)用Que.prototype.getName方法
alert(Que.prototype.getName.apply(nameObject)); // zhangfei
4.參數(shù)
當(dāng)函數(shù)被調(diào)用時颂斜,它會被免費(fèi)贈送一個arguments參數(shù)夫壁,它是傳入實(shí)參的集合
這使得編寫一個無形成的函數(shù)成為可能
var addNoParam = function () {
var res = 0;
for (var i = 0, len = arguments.length; i < len; i++) {
res += arguments[i];
}
return res;
}
alert(addNoParam(1, 3, 4, 5)); // 13
5.返回
當(dāng)一個函數(shù)被調(diào)用時,它從第一條語句開始執(zhí)行沃疮,直到最后的}結(jié)束
return語句可以讓函數(shù)提前退出執(zhí)行盒让。當(dāng)return語句被調(diào)用,那么return之后的語句不會被執(zhí)行
當(dāng)函數(shù)是構(gòu)造器函數(shù)模式調(diào)用時司蔬,返回this糯彬,并非一個對象
return返回默認(rèn)為undefined,如果沒有指定