前端this指向问题

前端this指向问题

一、this指向Window

function zr(){
    var username = "睿睿";
    console.log(this.username ); //undefined
    console.log(this); //Window
}
zr();
//相当于
window.zr();

二、this指向调用者
fn是通过zr.fn()执行的,那this指向就是对象zr

var zr = {
    username:"睿睿",
    fn:function(){
        console.log(this.username);  //睿睿
    }
}
zr.fn();

三、this指向上一级对象

var zr = {
    a:1,
    b:{
        a:2,
        fn:function(){
            console.log(this.a); //2
        }
    }
}
zr.b.fn();

所以:普通函数中的this如果没有被上一级的对象所调用,那么this指向的就是window;如果有被上一级的对象所调用,且不管其有多少上一级,this指向的也只是它上一级的对象;

四、构造函数的this

function Fn(){
    this.username = "睿睿";
}
var zr = new Fn();
console.log(zr.username ); //睿睿

new就相当于复制了Fn到对象zr中;且new可以改变this的指向,将this指向对象zr
注意:当this碰到return时,要看return的是什么类型;若return的是一个对象(null除外),那么this指向的就是那个对象;反之this还是指向函数的实例;

猜你喜欢

转载自blog.csdn.net/a791226606/article/details/106242338