1.函數(shù)對象
函數(shù)就是對象。
對象是“名\值”對的集合并擁有一個連接到對象原型的隱藏的連接
函數(shù)對象連接到Function.prototype上
每個函數(shù)對象在創(chuàng)建時,隱藏兩個屬性,即函數(shù)的上下文和實現(xiàn)函數(shù)行為的代碼
每個函數(shù)在創(chuàng)建時都會攜帶一個prototype屬性,它的值擁有一個constructor屬性且值為該對象的函數(shù)
2.函數(shù)字面量
函數(shù)字面量 = function關鍵字 + 函數(shù)名(這里省略) + 參數(shù)(a, b) + body函數(shù)體
var add = function (a, b) {
return a + b;
}
alert(add(3, 4)); // 73.調用
調用一個函數(shù)即暫停當前函數(shù)并把執(zhí)行權交給新函數(shù)。
調用的函數(shù)除了接受實參外,還將接受this和arguments兩個參數(shù)
this的值取決于調用的模式:方法調用模式、函數(shù)調用模式、構造器模式和apply調用模式
arguments表示接受實參的偽數(shù)組
方法調用模式
當一個函數(shù)被保存為一個對象的屬性,我們將這個函數(shù)成為方法
當這個方法被調用時,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當一個函數(shù)被非對象調用時,那么它就是方法調用模式
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構造器調用模式
如果一個函數(shù)在其前面加new調用,那么將創(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()); // noApply調用模式
apply函數(shù)構建一個數(shù)組并去其去調用函數(shù)
它接受兩個參數(shù):第一個是將被綁定this的值,第二個是一個數(shù)組
var array = [3, 4];
alert(add.apply(null, array)); // 7, this沒有被強制綁定值,即為window
var nameObject = {
name : "zhangfei"
}
// 將this綁定到nameObject中,并且調用Que.prototype.getName方法
alert(Que.prototype.getName.apply(nameObject)); // zhangfei4.參數(shù)
當函數(shù)被調用時,它會被免費贈送一個arguments參數(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)); // 135.返回
當一個函數(shù)被調用時,它從第一條語句開始執(zhí)行,直到最后的}結束
return語句可以讓函數(shù)提前退出執(zhí)行。當return語句被調用,那么return之后的語句不會被執(zhí)行
當函數(shù)是構造器函數(shù)模式調用時,返回this,并非一個對象
return返回默認為undefined,如果沒有指定