函數(shù)是一系列過程的抽象。
~~~
//十進(jìn)制轉(zhuǎn)二進(jìn)制
var D2B = function (num) {
var B = "";
do {
var rest = num % 2;
if (rest === 0) {
B = 0 + B;
}
else {
B = rest + B;
num = num - rest;
}
num = num / 2;
} while (num !== 0);
return B;
};
console.log(D2B(251));//11111011
~~~
使用函數(shù),相當(dāng)于執(zhí)行抽象函數(shù)時所用的一系列過程。
~~~
var num = 251;
var B = "";
do {
var rest = num % 2;
if (rest === 0) {
B = 0 + B;
}
else {
B = rest + B;
num = num - rest;
}
num = num / 2;
} while (num !== 0);
console.log(B);//11111011
~~~
僅此而已。
# ES中的函數(shù)
ES中的函數(shù)由函數(shù)名,參數(shù)列表,函數(shù)體組成,在使用上有著幾個約束:
* 能接受0至n個值作為參數(shù),能求得0或1個值作為返回值。
* 函數(shù)內(nèi)定義的變量,只能在該函數(shù)內(nèi)生效。
* 執(zhí)行函數(shù)時在函數(shù)內(nèi)綁定this的引用。
* 執(zhí)行函數(shù)時在函數(shù)內(nèi)生成包含所有參數(shù)的arguments對象。
示例:
~~~
var func = function () {
return 2017;
};
var foo = function (f) {
console.dir(f());
};
foo(func);//打印2017
~~~
