一次学会this指向

一、this指向的定律

  1. 函数声明的时候决定不了this指向,在调用的时候决定,谁调用了这个函数就指向谁;
  2. this永远指向最近一个调用他的对象;
  3. 构造函数会自动把this指向实例对象;
  4. 如果构造函数内部有return出对象,那么this指向这个return出的对象;

二、代码片段

// 1 window调用了a()
function a(){
    var user = "赵敏";
    console.log(this.user); //undefined
    console.log(this); //Window
}
a();

// 2 o 调用了fn()
var o = {
    user:"赵敏",
    fn:function(){
        console.log(this.user);  //赵敏
    }
}
o.fn();

// 3 // fn()最近的b调用了fn()
var o = {
    a:10,
    b:{
        a:12,
        fn:function(){
            console.log(this.a); //12
        }
    }
}
o.b.fn();

// 4 最终是window调用了j() ,j 调用了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();

// 5 this指向了a
function Fn(){
    this.user = "赵敏";
}
var a = new Fn();
console.log(a.user); //赵敏

// 6 this指向return出的对象
function fn()  
{  
    this.user = '赵敏';  
    return {};  
}
var a = new fn;  
console.log(a.user); //undefined

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值