函數(shù)是一個特殊的對象,所以可以有自己的屬性和方法,甚至可以用Function()構(gòu)造函數(shù)來創(chuàng)建新的函數(shù)
length
函數(shù)有只讀的length屬性,它代表函數(shù)定義的參數(shù)的個數(shù)。要與arguments.length區(qū)分開,后者是函數(shù)調(diào)用時傳入?yún)?shù)的個數(shù)。
prototype
每個函數(shù)都包含不同的原型對象。當(dāng)函數(shù)用作構(gòu)造函數(shù)的時候,新創(chuàng)建的對象會從原型對象上繼承屬性。
call()和apply()
call和apply的作用相同,可以將對象引用為this,只是參數(shù)傳入的方式不同。
function add(c,d){
return this.a + this.b + c + d;
}
var s = {a:1, b:2};
console.log(add.call(s,3,4)); // 1+2+3+4 = 10
console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14
bind
當(dāng)在函數(shù)f()上調(diào)用bind()方法并傳入一個對象o作為參數(shù),這個方法將返回一個新的函數(shù),調(diào)用新的函數(shù)會把原始函數(shù)f()方做o的方法來調(diào)用。
function add(){return this.x+this.y}
var o = {x:10,y:20}
var fun = add.bind(o)
fun() //30
toString
函數(shù)的toString方法大多返回函數(shù)的源碼
//承接上面的代碼
fun.toString()
"function () { [native code] }"
add.toString()
"function add(){return this.x+this.y}"
Function構(gòu)造函數(shù)
除了使用function關(guān)鍵字定義,函數(shù)可以通過Function構(gòu)造函數(shù)來定義
以下兩種方式定義是等價的
var f1 = new function("x","y","return x*y")
var f2= function(x,y){return x*y}
- Function構(gòu)造函數(shù)可以傳入任意數(shù)量字符串,最后一個字符串是函數(shù)體,前面的都是參數(shù)。
- 函數(shù)體可以包含任意條語句,可以用分號分割。
- 如果不需要參數(shù),只需要傳入一個字符串作為函數(shù)體。
- Function構(gòu)造函數(shù)允許Javascript在運行時動態(tài)創(chuàng)建并編譯函數(shù)
- 如果在循環(huán)中使用Function構(gòu)造函數(shù),效率會比較低。但是循環(huán)中的嵌套函數(shù)和函數(shù)定義表達式不會每次都重新編譯,效率會比較高。
- Function構(gòu)造函數(shù)創(chuàng)建的函數(shù)不使用詞法作用域,它總是在頂層執(zhí)行。
var scope = 'global scope'
function consFun(){
var scope = "local scope"
return new Function("return scope")
}
consFun()() //"global scope"