在函数中this到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了。
情况1:构造函数
function Foo(){ this.name="王福朋" this.year=1988; console.log(this);//Foo{name:"王福朋",year:1988} } var f1=new Foo(); console.log(f1.name);//王福朋 console.log(f1.year);//1988
以上代码中,如果函数作为构造函数用,那么其中的this就代表它即将new出来的对象。
function Foo(){ this.name="王福朋" this.year=1988; console.log(this);//Window } Foo();
这种情况下this是window,因为Foo函数只是当做普通函数执行,并没有实例化
情况2:构造函数中的prototype中
function Foo(){ this.name="王福朋" this.year=1988; console.log(this);//Foo{name:"王福朋",year:1988} } Foo.prototype.getName=function () { console.log(this.name) } var f1=new Foo(); f1.getName() //王福朋
在Fn.prototype.getName函数中,this指向的是f1对象。因此可以通过this.name获取f1.name的值。
其实,不仅仅是构造函数的prototype,即便是在整个原型链中,this代表的也都是当前对象的值。
情况3:函数作为对象的一个属性被调用时
var obj={ x:10; fn:function(){ console.log(this); console.log(this.x);//10 } }; obj.fn();
如果fn函数被赋值到了另一个变量中,并没有作为obj的一个属性被调用,那么this的值就是window,this.x为undefined。
var obj={ x:10; fn:function(){ console.log(this);//Window console.log(this.x);//undefined } }; var fn1=obj.fn; fn1();
情况4:函数用call或者apply调用
当一个函数被call和apply调用时,this的值就取传入的对象的值。
var obj={ x:10; }; var fn=function(){ console.log(this);//Object{x:10} console.log(this.x);//10 } fn.call(obj);
情况5:全局调用普通函数
var x=10; var fn=function(){ console.log(this);//Window console.log(this.x);//10 } fn();