注意: console.log()永遠返回undefined挪钓,它打印出來的值和返回的值沒有關系。
函數(shù)的5種聲明方式
- 具名函數(shù)
function f(input1, input2) {
return undefined
}
console.log(f) //沒有問題洒闸,可以在函數(shù)外部訪問f
- 匿名函數(shù)
var f
f = function (input1, input2) {
return undefined
}
//匿名函數(shù)必須賦值給一個變量
- 具名函數(shù)賦值給變量
var x
x = function f(input1, input2) {
return undefined
}
console.log(f) //會報錯顯示f: undefined
//它只能在function f(input1, input2){只能在這里訪問f}大括號內部訪問到f
- window.Function
var f
f = new Function('x', 'y', 'return x + y')
f(1, 2)
//output:
3
- 箭頭函數(shù)
sum = (x, y) => {return x + y}//箭頭函數(shù)沒有名字染坯,只能把它賦值給一個變量,相當于匿名函數(shù)的簡化
sum(1,2)
//output:
3
sum = (x, y) =>{
var n = x * 2;
var m = y * 3;
return n + m
}
sum(1,2)
//output:
8
//如果只有一個返回值丘逸,可以把{}和return一起去掉
sum = (x, y) => x + y
sum(1,2)
//output:
3
//如果參數(shù)只有一個单鹿,則()可以去掉
sq = n => n * n
sq(2)
//output:
4
函數(shù)的name屬性
一個垃圾屬性
函數(shù)的本質
函數(shù)的本質就是可執(zhí)行代碼的對象
// 函數(shù)調用的兩種方法
f(x1, x2) //小白方法
f.call(undefined, x1, x2) //盡量用這種
this和arguments
f.call(undefined, x1, x2)
1. call的第一個參數(shù)可以用this得到
2. call的后面的參數(shù)可以用arguments得到
1. this
在普通模式下,如果this是undefined深纲,瀏覽器會把this變成window(小寫)
在嚴格模式下仲锄,如果this是什么就是什么。
所以this就是call的第一個參數(shù)囤萤。
2. arguments
arguments是call后面的參數(shù)組成的偽數(shù)組(proto不是Array.prototype昼窗,或者它的原型鏈中沒有Array.prototype)
函數(shù)作用域
- 第一題
var a = 1
function f1(){
f2.call()
console.log(a)
var a = 2 //新手永遠不記得變量提升
function f2(){
var a = 3
console.log(a)
}
}
f1.call()
console.log(a)
看到代碼一定先做聲明提升(變量提升)
var a
a = 1
function f1(){
var a
function f2(){
var a
a = 3
console.log(a)
}
f2.call()
console.log(a) //undefined
a = 2
}
f1.call() // 3 undefined
console.log(a) // 1
- 第二題
var a = 1
function f1(){
console.log(a) //undefined
var a = 2
f4.call() // 1
}
function f4(){
console.log(a)
}
f1.call()
var a = 1
function f1(){
console.log(a) //undefined
var a = 2
f4.call() // 3
}
function f4(){
console.log(a) //函數(shù)f4作用域內沒有a這個變量,所以它會從它的父作用域內找涛舍,它的父作用域是全局作用域澄惊,其中:var a = 1,但是在執(zhí)行f1.call()之前(f4.call()是通過f1.call()調用的),a的值被重新賦值為a = 3掸驱,所以f4.call()打印出的值為3
}
a = 3
f1.call()
var a = 1
function f4(){
console.log(a)//2
}
a = 2
f4.call()
var a = 1
function f4(){
console.log(a)//1
}
f4.call()
a = 2
-
第三題
當鼠標點擊選項3時肛搬,console.log(i)打印出的值為6;因為for循環(huán)在納秒級時間內就結束了毕贼,當你鼠標去點選項3時温赔,已經是6了。
閉包
如果一個函數(shù)使用了它范圍外的值鬼癣,那么(這個函數(shù)+這個變量)就叫做閉包
var a = 1
function f(){
console.log(a) // 2
}