函數(shù)的定義方式
1.自定義函數(shù)(命名函數(shù))
funtion fn(){};
2.函數(shù)表達(dá)式(匿名函數(shù))
var fun = funtion fn(){};
3.使用new Funtion('p1', 'p2', '函數(shù)體')
//函數(shù)體用字符串的形式寫入
var f = new Funtion('p1', 'p2', 'console.log(p1+p2)');
f(1, 2)
所有函數(shù)都是Funtion的一個(gè)實(shí)例(對(duì)象)
函數(shù)也是一種對(duì)象
函數(shù)的調(diào)用方式
1.普通函數(shù)
funtion fn(){ console.log('nihao')};
//調(diào)用
fn();
//或者
fn.call()
2.對(duì)象的方法
var x = {
sayHi:funtion(){
console.log('nihao');
}
}
//調(diào)用
x.sayHi();
3.構(gòu)造函數(shù)
funtion Star(){};
//調(diào)用
new Star();
4.綁定事件函數(shù)
btn.onclick = function(){};
//點(diǎn)擊按鈕進(jìn)行調(diào)用
5.定時(shí)器函數(shù)
setInterval(funtion(){}, 1000);
6.立即執(zhí)行函數(shù)
(funtion(){
console.log('nihao');
})();
this的指向問題
this的指向是當(dāng)我們調(diào)用函數(shù)的時(shí)候確定的窗慎,調(diào)用方式的不同決定了this的指向不同
?調(diào)用方式???????????this指向
普通函數(shù)調(diào)用 ????????window(普通函數(shù)是window調(diào)用的)
構(gòu)造函數(shù)調(diào)用 ????????實(shí)例對(duì)象,原型對(duì)象里面的方法也指向?qū)嵗龑?duì)象
對(duì)象方法調(diào)用 ????????該方法所屬對(duì)象
事件綁定方法 ????????綁定事件的對(duì)象
定時(shí)器函數(shù) ??????????window
立即執(zhí)行函數(shù) ????????window
改變函數(shù)內(nèi)部this的指向
JavaScript提供了一些函數(shù)方法幫我們更優(yōu)雅的處理函數(shù)內(nèi)部的this指向問題征讲,常用的有bind()层亿、call()、apply()三個(gè)方法
1.call方法
var t = {
name:'tom'
}
funtion fn(){
console.log(this);
}
fn.call() //這時(shí)候fn函數(shù)中的this指向window
fn.call(t) //這時(shí)fn函數(shù)中的this指向了t對(duì)象
這個(gè)特性可以用在繼承中
funtion Father(uname , age){
this.uname = uname;
this.age = age;
}
funtion Son(uname, age){
//通過call函數(shù)將father中的this指向了son
//son繼承了father的構(gòu)造函數(shù)拔莱,擁有了uname和age這兩個(gè)屬性
Father.call(this, uname, age);
}
2.apply方法
apply()和call()作用一樣(參數(shù)不同)碗降,可以調(diào)用一個(gè)函數(shù),簡(jiǎn)單理解為調(diào)用函數(shù)的方式塘秦,但是它可以改變函數(shù)的this指向
fun.apply(thisArg, [argsArray]) (參數(shù)必須是數(shù)組(偽數(shù)組))
apply主要應(yīng)用在數(shù)組方面
//數(shù)組中沒有求最大最小值的方法讼渊,但是Math中有
//可以使用apply方法實(shí)現(xiàn)
var arr = [1, 2, 3, 4, 1];
var max = Math.max.apply(Math, arr);
var min = Math.max.apply(Math, arr);
console.log(max, min);
3.bind方法
bing()方法不會(huì)調(diào)用函數(shù),但是可以改變函數(shù)內(nèi)部this的指向
fun.bind(thisArg, arg1, arg2, ...)
返回原函數(shù)改造后的一個(gè)拷貝