首先:在函数中this 到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了。
(this 对象是在运行时基于函数的执行环境绑定的)
1.构造函数
如果函数作为构造函数用,那么它里面的 this 就代表它将要 new 出来的的对象
function A(){
this.name="xiaoming";
this.age="7";
console.log(this); //结果:A {name: "xiaoming", age: "7"}
}
var a=new A();
console.log(a.name); //结果:xiaoming
如果我们直接调用A函数,而不是 new A(),结果就不一样了。(此时 this 就是 window)
function A(){
this.name="xiaoming";
this.age="7";
console.log(this); //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
}
A(); //注意!!!
2.函数作为一个对象的属性
函数作为一个对象的属性,并作为一个对象的属性被调用,该函数中的 this 指向该对象
var obj={
x:10,
fn:function(){
console.log(this); //结果:{x: 10, fn: ƒ}
console.log(this.x); //结果:10
}
};
obj.fn();
注意:该函数必须作为一个对象的属性被调用,如下将函数赋到一个变量中并调用,此时this 值为 window
var obj={
x:10,
fn:function(){
console.log(this); //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
console.log(this.x); //undefined
}
};
var fn1=obj.fn;
fn1();
还有一种情况也为 (this =window)必须注意一下:
var obj={
x:10,
fn:function(){
function f(){
console.log(this); //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
console.log(this.x); //undefined
}
f();
}
};
obj.fn();
3.函数用call 或 apply
一个函数用call 或 apply调用时,this 的值取传入对象的值
var obj={
x:10,
};
var fn=function(){
console.log(this); //结果:{x: 10}
console.log(this.x); //结果:10
};
fn.call(obj); //使用call 相当于 this=obj;
4.全局 / 调用普通函数
全局环境下,this 永远为 window!
console.log(this===window) //结果:true
var fn=function(){
console.log(this); //结果:Window {postMessage: ƒ, blur: ƒ, focus: ƒ,....}
console.log(this.x); //结果:undefined
}
fn();
其实总的来说:
在全局环境中 this 等于 window
当函数被作为某个对象的方法调用时,this 就代表那个对象