前言: 前端這兩年的新技術鋪天蓋地,各類框架、工具層出不窮眼花繚亂。最近打算好好複習下 js 基礎,夯實的基礎纔是學習新技術的基石。本文做爲讀書筆記簡單的總結下 js 函數的基礎知識。前端
函數對象經過函數字面量來建立:數組
var add = function(a,b){
return a+b;
};
函數字面量包括四個部分:閉包
注意:一個內部函數除了能夠訪問本身的參數和變量,同時也能夠自由的訪問父函數的參數和變量。用過這種函數字面量建立的函數對象包含一個鏈接到外部上下文的鏈接。這個被稱爲閉包app
當有個函數被保存爲對象的一個屬性是,咱們稱他爲一個方法。當以個方法被調用時,this被綁定到該對像。框架
var myObject = { value: 0, increment: function (icn) { this.value += typeof inc === 'number' ? icn: 1; } } myObject.increment(); console.log(myObject.value); myObject.increment(2); console.log(myObject.value);
方法可使用this訪問本身所屬的對象。經過this可取可取的他們所屬對象的上下文的方法稱爲公共方法異步
myObject.double = function(){ var that = this ; var helper = function(){ that .value = add(that.value,that.value); } helper(); //以函數的形式調用helper } //以方法的形式調用double myObject.double(); console.log(myObject.value);
//建立一個構造器函數Quo var Quo = function(string){ this.status = string; }; //給Quo提供一個get_status的公共方法 Quo.prototype.get_status = function(){ return this.status; }; //構造一個Quo實例 var myQuo = new Quo("hello world"); console.log(myQuo.get_status());
var array = [3,4];
var sum = add.apply(null,array);
var statusObject = { status: 'A-ok' }; var status = Quo.prototype.get_status.apply(statusObject); console.log(status); //A-OK
arguments並非一個真正的數組,擁有一個length屬性,但它沒有任何數組的方法
var a = 2;
function foo(){
var a =3;
consloe.log(a);//3
}
foo();
consloe.log(a);//2
var que = function(status){ return { get_status: function(){ return status; } } } var myQuo = que("hello"); console.log(myQuo.get_status());
get_status方法並非訪問參數的副本,他訪問的就是參數的自己,這就是閉包,保護status爲私有屬性函數
function a(){ console.log('執行a函數'); setTimeout(function(){ console.log("執性a函數的延遲函數") },1000) }; function b (){ console.log('執行函數b') } a(); b();
以上代碼會先執行函數a,並且不會等到a中的延遲函數執行完才執行函數b, 在延遲函數被觸發的過程當中就執行了函數b,當js引擎的event 隊列空閒時纔會去執行隊列裏等待的setTimeout的回調函數,這就是一個異步的例子工具
如下是谷歌得出的結論學習
callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
var foo= (function(){ var something = 'cool'; var another =[1,2,3]; function doSomething(){ console.log(something); } function doAnother(){ console.log(another.join(' ! ')); } return{ doSomething: doSomething, doAnother: doAnother } })(); foo.doSomething(); foo.doAnother();