定义:
函数是一个可被重复使用的代码块,能被其他的代码或者自身调用。函数能接受参数,并且也能返回值,函数还是一个对象。
函数的类型:
匿名函数:顾名思义,没有名字的函数,通常作为回调函数使用
function(){}
普通函数:
// 函数声明
function say(){}
// 函数表达式
var say = function(){}
内部函数与外部函数:
被一个函数包含着的函数即是内部函数,而包含着另一个函数的函数即是外部函数,如下代码所示,getSquare
为内部函数,而getHypotenuseLength
为外部函数:
function getHypotenuseLength(a,b){
function getSquare(x) {
return x * x;
}
return Math.sqrt(getSquare(a)+getSquare(b));
}
递归函数:
递归函数常常在自身内部调用这自己,如使用下面代码用来计算阶乘:
function getFactorial(x) {
if(x === 1){
return x;
}
return x * getFactorial(x-1);
}
立即执行函数(Immediately Invoked Function Expressions ,IIFE)
当函数被定义并载入浏览器时便执行的函数,如下定义了一个立即执行函数:
(function hello(){
console.log('Hello World!');
})();
调用函数
当函数被定义后并不会被执行,若想执行一个函数,则需要使用函数名来调用(回调函数则需要当事件发生时被调用)。
如我们之前定义的getHypotenuseLength
,这个函数被定义用来获取直角三角形的斜边长,接受两个参数(直角的两个边长),并返回计算后的直角变长.
getHypotenuseLength(3,4);//5
函数声明提前
函数被调用之前必须存在与调用作用域中,但是函数声明将会被提升,如下代码所示:
hello();
function Hello(){console.log('Hello');}
当使用函数表达式时,不会起到被提升,如下代码:
console.log(hello);//undefined
hello();//TypeError: hello is not a function
var hello = function(){console.log('Hello');}
在这里,第一句输出undefined
是因为变量声明提升,但此时hello也仅仅是被声明了却还没有被赋值,所以当执行到第二句的时候hello
依然是undefined所以就报出了类型错误。
函数作用域
函数外部的不可以访问到在函数内部定义的变量与函数等,函数内部可以访问到在函数外部定义的变量与函数…
tip:JavaScript作用域为函数作用域。
var earth = 'Earth.O2';
function sea() {
var water = 'Sea.O2';
function fish() {
var meat = 'Fish.proteins';
console.log(earth); //Earth.O2
console.log(water); //Sea.O2
}
fish();
console.log(earth); //Earth.O2
console.log(meat); //meat id not defined
}
sea();
console.log(water); //water id not defined
console.log(meat); //meat id not defined