JS中this的7种指向问题

什么是this?
this --> 关键字;在JS中有特殊的含义。
注意: this 不能放到等号的左边;
下面看一下在不同的情景下,this不同的指向情况

1. 在全局作用域,this指向window;this 和window是同一块空间地址;

        //直接在html文件中输出this,指向的window
        console.log(this);// window 
        //下面这两个含义是一样的
        window.alert()
        this.alert();

2. 给元素的事件绑定的函数中的this,指向了当前被点击的那个元素;

    <div id="box">点我</div>
    <div id="box1">点我1</div>

    <script>
           box.onclick = function(){
            //这里面的this : 是个对象; 
            console.dir(this===box); // 空间地址相同;
            box.style.color="red";//给文字改变颜色
            this.style.color="red";
            //this=100;// this 不能放到等号的左边;
        }
    </script>

3.看函数执行前有没有".",如果要是没有,那么函数中的this指向window,如果有"." ,那么点前面是谁,this就指向谁;

        var obj = {
            m:1,
            fn:function(){
                console.log(this);
            }
        }
        var f = obj.fn;
        console.log(f==obj.fn);//true
        obj.fn();//this==>obj
        f();//this==>window

4. 自执行函数中this 永远指向window;

       (function(){
            console.log(this);// window
        })();
        var obj = {
            fn:(function(){
                console.log(this);// window
                return function(){
                    console.log(this); // window
                }
            })()
        }
         var f= obj.fn;
         f();

5. 回调函数中的this一般都指向window;

        setTimeout(function(){
            console.log(this);//window
        },1000);
        var ary=[1,2,3,4]
        ary.map(function(){
            console.log(this);//会输出4个window
        })

6.构造函数中的this指向实例;

7.call,apply,bind 可以改变this指向;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值