JavaScript 基礎深刻——函數
函數基礎
什麼是函數?
- 實現特定功能的 n 條語句的封裝體
- 只有函數是能夠執行的,其它類型的數據不能執行
爲何要用函數?
如何定義函數?
function fn1 () { //函數聲明
console.log('fn1()')
}
var fn2 = function () { //表達式
console.log('fn2()')
}
如何調用(執行)函數?
-
test()
:直接調用
-
obj.test()
:經過對象調用
-
new test()
:new 調用
-
test.call/apply(obj)
:臨時讓test
成爲obj
的方法進行調用
var obj = {}
function test2 () {
this.xxx = 'atguigu'
}
// obj.test2() 不能直接, 根本就沒有
test2.call(obj) // obj.test2() // 能夠讓一個函數成爲指定任意對象的方法進行調用
console.log(obj.xxx) // 'atguigu
回調函數
什麼函數纔是回調函數?
- 你定義的
- 你沒有調用
- 但最終它執行了(在某個時刻或某個條件下)
常見的回調函數
- dom 事件回調函數==> 發生事件的dom元素
- 定時器回調函數 ===> window
- ajax 請求回調函數
- 生命週期回調函數
document.getElementById('btn').onclick = function () { // dom事件回調函數
alert(this.innerHTML)
}
//定時器
// 超時定時器
// 循環定時器
setTimeout(function () { // 定時器回調函數
alert('到點了'+this)
}, 2000)
IIFE
(當即執行函數)
理解
- 全稱:
Immediately-Invoked Function Expression
做用
- 隱藏實現
- 不會污染外部(全局)命名空間
- 用它來編碼js模塊
;(function () { //匿名函數自調用
var a = 3
console.log(a + 3)
})()
var a = 4
console.log(a)
;(function () {
var a = 1
function test () {
console.log(++a)
}
window.$ = function () { // 向外暴露一個全局函數
return {
test: test
}
}
})()
$().test() // 1. $是一個函數 2. $執行後返回的是一個對象
函數中的this
this
是什麼?
- 任何函數本質上都是經過某個對象來調用的,若是沒有直接指定就是window
- 全部函數內部都有一個變量
this
- 它的值是調用函數的當前對象
如何肯定this
的值?
-
test()
: window
-
p.test()
: p
-
new test()
: 新建立的對象
-
p.call(obj)
: obj
function Person(color) {
console.log(this)
this.color = color;
this.getColor = function () {
console.log(this)
return this.color;
};
this.setColor = function (color) {
console.log(this)
this.color = color;
};
}
Person("red"); //this是誰? window
var p = new Person("yello"); //this是誰? p
p.getColor(); //this是誰? p
var obj = {};
p.setColor.call(obj, "black"); //this是誰? obj
var test = p.setColor;
test(); //this是誰? window
function fun1() {
function fun2() {
console.log(this);
}
fun2(); //this是誰? window
}
fun1();