03深入理解this指向问题

在javascript中所用到的this有以下几个方面:
1 全局下的this 在非严格模式情况下 下面的this都是window

2、对象中的this
如果调用对象中的方法,那么方法中的this指向这个调用者
方法中的this就是当前的对象
如果直接给属性赋一个,this.a 其中a已经定义,此时this指向window,打印得到undefined
3、回调函数中的this指向

事件时特殊的回调函数  事件回调函数中this都是被侦听的对象
所有的函数一旦被写再一个方法中,这个函数就是匿名的回调函数,在该函数中this指向window
function ab(fn){
    fn()
}
function cd() {
    console.log(this);
}
ab(cd);  //window
var obj= {
    a:function(fn){
        fn();
    },
    b:function(){
        //指向window
        console.log(this);
    }
}
obj.a(obj.b);

4、ES6的
如果是静态属性或者方法,

一旦被设置为静态属性,this指向都会被设置为当前的类名Box
对于面向对象语言来说,一般在静态属性和方法中不允许使用this

class Box{
    //这里的内容是constructor执行后再进行赋值的
    // static b=2;
    //这里的this指向的是Box类名
    // static a = this.b;
       b=22;
       //这里的this指向b
       a=this.b;
    constructor(){
        //   这里的this指向实例化的对象
        console.log(this)
        // this.b=3;
    }
    play(){
        console.log(this.a,this);
        // 这里的this指向实例化的对象
    //
    }
    static run(){
        console.log(Box);
    //       这里的this指向为当前类名Box
    //     对于面向对象语言来说,一般在静态属性和方法中不允许使用this
    }
}
var b = new Box();
   b.play();
   Box.run();

继承后,静态的方法也会被继承
class Ball extends Box{
constructor(){
super();
}
}
Ball.run();得到一个Ball类名

5 es5

es5的
function Box(){
    console.log(this);
    //这里的this 构造函数的this new 出的对象
    this.c();
}
Box.a=function(){
    //这里的this指向    Box
    console.log(this)
}
Box.b=3;
Box.prototype.c=function(){
    // 这里的this指向当前调用该方法的实例对象
    console.log(this)
}
Box.prototype.d = 30;


var h = new Box();
console.log(h);
console.dir(Box)
Box.a();
// b对象中是没有c这个对象属性的,因此就去原型链中找到最近的play方法
//console.log(dir);
h.c();

6 箭头函数
所有箭头函数的this都是指向当前函数外的this指向

var obj={
//     a:()=>{
//         console.log(this);//this--->window
//     },
//     b:function(){
//         console.log(this);//this--->obj
//     },
//     c(){
//         console.log(this);//this--->obj
//     }
// }


var obj={
//     a:function(){
//         setTimeout(()=>{
//             // 因为本来是回调函数,this统一都会被执行window
//             // 但是使用了箭头函数,就会全部把这里this指向setTimeout外的this指向,也就是obj
//             console.log(this);
//         },100)
//     }
// }
// obj.a();‘

7、7 call apply bind
当使用call,apply,bind都会将函数中this的指向重新指向到对应的对象

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值