1、全局环境下:this始终指向全局对象(window),无论是否严格模式
var o = {
a:10,
b:{
// a:12,
fn:function(){
console.log(this.a); //undefined
}
}
}
o.b.fn();
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
this永远指向的是最后调用它的对象,也就是看它执行的时候是谁调用的,第二段代码中虽然函数fn是被对象b所引用,但是在将fn赋值给变量j的时候并没有执行所以最终指向的是window,这和第一段代码是不一样的,第一段代码是直接执行了fn。
2、函数上下文调用
(1)函数直接调用:非严格模式下this默认指向全局对象window;严格模式下this为undefined
(2)对象中的this:对象内部方法的this指向调用这些方法的对象,函数的定义位置不影响其this指向,this指向只和调用函数的对象有关;多层嵌套的对象,内部方法的this指向离被调用函数最近的对象
(3)原型链中的this:原型链中的方法的this指向调用它的对象
3、构造函数中的this:构造函数中的this与被创建的新对象绑定
4、DOM事件处理函数中的this:当函数被当做监听事件处理函数时, 其 this 指向触发该事件的元素 (针对于addEventListener事件)
5、内联事件中的this
(1)当代码被内联处理函数调用时,它的this指向监听器所在的DOM元素,如:
<button onClick="console.log(this)">show me</button>
(2)代码被包括在函数内部执行时,其this指向等同于 函数直接调用的情况,即在非严格模式指向全局对象window, 在严格模式指向undefined
<button onClick="(function(){ console.log(this); })()">show me</button>
6、setTimeout和setInterval中的this:对于延时函数内部的回调函数的this指向全局对象window
7、箭头函数中的this:由于箭头函数不绑定this, 它会捕获其所在(即定义的位置)上下文的this值, 作为自己的this值
8、当this遇到return时
function fn()
{
this.user = 'Hello World!';
return {};
}
var a = new fn;
console.log(a.user); //undefined
function fn()
{
this.user = 'Hello World!';
return function(){};
}
var a = new fn;
console.log(a.user); //undefined
function fn()
{
this.user = 'Hello World!';
return 1;
}
var a = new fn;
console.log(a.user); //Hello World!
function fn()
{
this.user = 'Hello World!';
return undefined;
}
var a = new fn;
console.log(a.user); //Hello World!
function fn()
{
this.user = 'Hello World';
return null;
}
var a = new fn;
console.log(a.user); //Hello World!
解析:如果返回值是一个对象,那么this指向的就是那个返回的对象,如果返回值不是一个对象那么this还是指向函数的实例
网友评论