一.不同的創(chuàng)建方式:
a.函數(shù)聲明:
function add(a,b){
return a+b;
}
b.函數(shù)表達(dá)式:
var add=function(a,b){
return a+b;
}
//IEF(Immediately Executed Function)立即執(zhí)行
(function(a,b){
return a+b;
})()
//函數(shù)對(duì)象作為返回值
return function(){
};
//NFE(Named Function Expression) 命名式函數(shù)表達(dá)式
var add=function foo(a,b){
return a+b;
}
c.Function構(gòu)造器
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);
二.不同的調(diào)用方式:
a.直接調(diào)用:
foo()
b.對(duì)象方法:
o.method()
c.構(gòu)造器:
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.一般函數(shù)的this(瀏覽器):
function f1(){
return this;
}
f1()===windonw; //true
嚴(yán)格模式下,f1()===undefined
c.作為對(duì)象方法的函數(shù)的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.對(duì)象原型鏈上的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.構(gòu)造器中的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
在構(gòu)造器中,沒(méi)有return語(yǔ)句時(shí),就返回該this,否則返回return的對(duì)象
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