函數(shù)的屬性
length屬性
用于記錄該函數(shù)擁有的參數(shù)數(shù)量(函數(shù)定義式的參數(shù)列表長度).
function f(a, b, c) {}
f.length

image.png
constructor屬性
Function含有構(gòu)造器屬性(constructor),構(gòu)造器屬性引用的是Function()構(gòu)造器函數(shù)
function f(a, b, c) {}
f.constructor

image.png
caller屬性
這個(gè)函數(shù)會(huì)返回一個(gè)調(diào)用該函數(shù)對(duì)象的外層函數(shù)引用.如果我們?cè)诤瘮?shù)B中調(diào)用函數(shù)A,那么只要在函數(shù)A中調(diào)用A.caller,結(jié)果就回得到函數(shù)B.
function A() {return A.caller;}
function B() {console.log(A());}
B();

image.png
當(dāng)在全局作用域中調(diào)用函數(shù)A,將得到nullimage.png
自定義屬性
函數(shù)是一種特殊的對(duì)象,因此函數(shù)可以像對(duì)象一樣擁有(或指定)屬性。自定義屬性的適用場(chǎng)景——靜態(tài)變量。
function f () {
return f.count++
}
f.count = 1
f[1] = 2 // 也可以使用[]指定屬性
f() // 1
f() // 2
函數(shù)的方法
call()和apply()
call()和apply()方法起到間接調(diào)用函數(shù)的作用。兩個(gè)方法都是顯示指定this值。區(qū)別:call方法的使用實(shí)參列表作為函數(shù)的實(shí)參,apply方法則是以數(shù)組形式傳遞參數(shù)。
function F () {
this.x = 1
this.y = 2
this.f1 = function () {
console.log('x: ' + this.x + ', y: ' + this.y)
return this
},
this.f2 = function (i, j) {
this.x = i
this.y = j
}
}
// 直接調(diào)用,f1方法的this就是調(diào)用該方法的對(duì)象
var f = new F()
var c = f.f1() // 輸出x: 1, y: 2。此時(shí)f1方法的this就是對(duì)象f
c === f // true
var m = {x: 5}
var m1 = f.f1.call(m) // x: 5, y: undefined。對(duì)象m沒有y屬性,因此this.y為undefined。 間接調(diào)用,此時(shí)f1方法的this===m 等價(jià)于f.f1.apply(m)
m === m1 // true
f.f2.call(m, 6, 5) // call方法的參數(shù)列表與f2方法一致,等價(jià)于f.f2.apply(m, [6, 5])
m.x // 6
m.y // 5
