一.不同的创建方式:
a.函数声明:
function add(a,b){
return a+b;
}
b.函数表达式:
var add=function(a,b){
return a+b;
}
//IEF(Immediately Executed Function)立即执行
(function(a,b){
return a+b;
})()
//函数对象作为返回值
return function(){
};
//NFE(Named Function Expression) 命名式函数表达式
var add=function foo(a,b){
return a+b;
}
c.Function构造器
var func=new Function('a','b','console.log(a+b);');
func(2,3);
var func=Function('a','b','console.log(a+b);');
func(2,3);
二.不同的调用方式:
a.直接调用:
foo()
b.对象方法:
o.method()
c.构造器:
new Foo()
d.call/apply/bind:
func.call(o)
三、this:
a.全局的this(浏览器):
console.log(this); //window
console.log(this.document===document); //true
this.a=2;
console.log(window.a); //37
b.一般函数的this(浏览器):
function f1(){
return this;
}
f1()===windonw; //true
严格模式下,f1()===undefined
c.作为对象方法的函数的this:
var o={
prop:37,
f:function(){
return this.prop;
}
}
console.log(o.f); //37
var o={prop:37};
function independent(){
return this.prop
}
o.f=independent;
console.log(o.f()); //37
c.对象原型链上的this:
var o={
f:function(){
return this.a+this.b;
}
};
var p=Object.create(o);
p.a=1;
p.b=4;
console.log(p.f()); // 5
d.构造器中的this:
function MyClass(){
this.a=37;
}
var o=new MyClass();
console.log(o.a); //37
function C2(){
this.a=37;
return{a:38};
}
o=new C2();
console.log(o.a); //38
在构造器中,没有return语句时,就返回该this,否则返回return的对象
e.call/apply方法与this
function add(c,d){
return this.a+this.b+c+d;
}
var o={a:1,b:3};
add.call(o,5,7); //1+3+5+7=16
add.apply(o,[10,20]); //1+3+10+20=34
f.bind方法与this
function f(){
return this.a;
}
var g=f.bind({a:'test'});
document.write(g()); //test