js中this指向

在这里插入图片描述

<button id='btn'>按钮</button>
    <script>
        //在全局作用下 this一般指向window
        //在严格模式下 this一般是undefined
        
        //在函数作用域下
        //在事件处理函数中,this一般指得是绑定事件的元素
        btn.onclick = function(){
            console.log(this);//btn
        } 

        对象调用方法时,this一般指向当前对象
        var obj = {
            name:'孙悟空',
            run :function(){
                console.log(this == obj);//true
            }
        }
        obj.run();

        在普通函数中 this一般指向window
        function fn(){
            console.log(this);//window
        }
        fn()

        在回调函数 this一般指向的也是window
        var arr = [1,2,3];
        arr.forEach((item,index)=>{
            console.log(this);//window
        })

        定时器中也为window
        setInterval(()=>{
            console.log(this);//window
        },666)

        用call的方法
        参数(新的指向,参数1,参数2);
        function fn(x,y){
            console.log(x,y,this);//1,2,'abc'
        }
        fn.call('abc',1,2)

        var obj = {
            name :'唐三',
            run : function(){
                console.log(this);//name:'唐浩',age:18
            }
        }
        var newObj = {
            name:'唐浩',
            age:18
        }
        obj.run.call(newObj)

        用apply的方法
        参数(新的指向,[参数1,参数2])
            
        function fn(x,y){
            console.log(x,y,this)
        }
        fn(1,2);
        fn.call(true,1,2);
        fn.apply(true,[1,2])

    </script>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值