js的this指向详解


注意:this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象(这句话有些问题,后面会解释为什么会有问题)

this指向的形式4种:

a.如果是一般函数,this指向全局对象window;

b.在严格模式下"use strict",为undefined.

c.对象的方法里调用,this指向调用该方法的对象.

d.构造函数里的this,指向创建出来的实例.

示例:一般函数(严格模式和非严格模式)

function a(){
    console.log(this); //Window
}
a(); //this:Window

function b(){
    "use strict";
     console.log(this); //undefined
}
b(); //this:undifined

示例:对象方法调用

var o = {
    user:"我的名字",
    fn:function(){
        console.log(this.user);  //我的名字
    }
}
o.fn();  //o调用的 this指向o 
window.o.fn();   //这个也是指向o

//这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象
var o = {
    a:10,
    b:{
        // a:12,
        fn:function(){
            console.log(this.a); //undefined
        }
    }
}
o.b.fn(); //this指向b

特殊情况:对象函数赋值给了变量

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指向的是window  (再次印证this是调用的时候才能确定的)

示例:构造函数的this指向

function Fn(){
    this.user = "我的名字";
}
var a = new Fn();
console.log(a.user); //我的名字

当构造函数中有return 时(这其实是构造出来的实例的问题)

//当return 一个对象的时候,构造出来的a是返回的对象,则a.user就是undifined

function fn()  
{  
    this.user = '我的名字';  
    return {};  
}
var a = new fn;  
console.log(a.user); //undefined

function fn()  
{  
    this.user = '我的名字';  
    return function(){};
}
var a = new fn;  
console.log(a.user); //undefined

//return 其它情况 a都返回fn
function fn()  
{  
    this.user = '我的名字';  
    return 1;
}
var a = new fn;  
console.log(a.user); //我的名字

function fn()  
{  
    this.user = '我的名字';  
    return undefined;
}
var a = new fn;  
console.log(a.user); //我的名字

function fn()  
{  
    this.user = '我的名字';  
    return null;
}
var a = new fn;  
console.log(a.user); //我的名字

需要了解改变this指向的方法,请移步

参考文章:

js