函数
1.定义一次,执行多次
2.是一种对象
函数调用
1.作为函数直接调用
foo();
2.作为对象方法
o.method();
3.作为构造函数
new Foo();
4.通过call()和apply()方法间接调用
func.call(o);
定义函数
函数声明
function add(a,b){ return a+b;}
函数表达式(特别适合定义只用一次的函数)
1.匿名函数赋值给一个变量
var add=function(a,b){
//do sth
};
2.立即执行函数表达式,()里面是一个匿名函数
(function(){
//do sth
})();
3.直接作为一个返回值
return function(){
//do sth
};
4.非匿名函数赋值给一个变量,不常见
var add=function foo(a,b){
//do sth
};
函数命名
1.动词或以动词为前缀的词组
2.第一个字符为小写,之后每个单词首字母大写(驼峰命名)
3.多个单词下划线(_)连接
4.一些用做内部函数或私有函数,以下划线为前缀
this
this没有作用域的限制,嵌套的函数不会从调用它的函数中继承来
1.嵌套函数作为方法调用,则this值指向调用它的对象
2.嵌套函数作为函数调用,则this不是全局对象(非严格模式),就是undefined(严格模式)
全局对象的this(浏览器)
console.log(this.document===document);//true
一般函数的this(浏览器)
function f(){
return this;
}
f()===window;//true,global object
作为对象方法的函数的this
如果想访问外部的this,就将其保存在一个变量里
var o={
m:function(){
var self=this; //把外部this赋值给一个变量
console.log(this===o); //true,this就是这个对象o
f();
function f(){
console.log(this===o); //false,
console.log(self===o); //true,self指向外部this
}
}
};