函数是一块js代码,被定义一次,但可以执行和调用多次。js中的函数也是对象,所以js函数可以向其他对象那样操作和传递,所以我们也常叫js中的函数为函数对象。
函数由函数名,参数列表,函数体组成。
创建函数的方式:
函数声明:function add(a,b){}
函数表达式:
var add = function(a,b){}
立即执行函数表达式:(function(){})()
将函数对象做为返回值:return function(){}
命名式函数表达式(不常见):
var add=function foo(a,b){}
alert(add === foo);//在ie8一下返回false,在ie9以上报错foo没有定义
函数构造器:var func = new Function();用不用new结果都是一样的。
函数声明与函数表达式的区别:
函数声明前置:
var num = add(1,2);
function add(a,b){};
this
全局作用域下的This指向全局对象,浏览器下的全局对象就是window
console.log(this.document === document);//true
console.log(this === window);//true
this.a = 37;
console.log(window.a);//37
一般函数的this
function f1(){return this;}
f1() === window;//true
如果是严格模式:
function f2(){
"use strict";
return this;
}
f2() === undefined;//true(this指向了undefined)
作为对象方法的函数的this:
对象原型链上的this:
get/set方法中的this也是指向get/set方法所在的对象
构造器中的this:
call/apply方法
bind方法
arguments
作用域
不同调用方式:
直接调用foo();
随想方法o.method();
构造器new Foo();
call/apply/bind : func.call(o);
不同创建方法