this的指向总结

总结前置:
1、普通函数:this指向window
2、对象函数:this指向调用它的对象
3、构造函数:没有return时,this指向调用它的对象,有return时,指向return返回的对象
4、绑定事件函数:this指向函数的调用者
5、定时器函数:this指向window
6、立即执行函数:this指向window
7、箭头函数:箭头函数没有this,只能向外层寻找,指向箭头函数被定义时所在的作用域。
8、使用apply,call,bind()可以更改函数this的指向。
使用方法:如

函数名.apply(对象);

使函数的this指向该对象。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>笔记:this的指向</title>
</head>
<body>

    <button id="btn">点击我</button>

    <script>
        // 1、普通函数:指向window
        function f1(){
            console.log(this);//Window

        }
        f1();

        // 2、对象函数:指向调用他的对象
        var obj={
            sayhi:function(){
                console.log(this);//{sayhi: ƒ}
            }
        }
        obj.sayhi();

        //3、构造函数
        function Star(name,age){
            this.name=name;
            this.age=age;
            console.log(this);//没有return函数,指向调用他的对象
        }
        let p1=new Star('李峋',20);

        function Star1(name,age){
            this.name=name;
            this.age=age;
            let p={name:'朱韵'};
            return p;//有return,指向返回的对象
        }
        let p11=new Star1('李峋',20);
        console.log(p11);

        //4、绑定事件函数:指向函数的调用者
        var btn = document.querySelector('button');
        btn.onclick = function () {
            console.log(this);  //<button id="btn">点击我</button>
        }

        //5、定时器函数:指向window
        setTimeout(function(){
            console.log(this);
        },1000);

        //6、立即执行函数:指向window
        (function(a){
            console.log(this);
        })(1);

        //7、箭头函数:箭头函数没有this,只能向外层寻找,指向函数被定义时所在的作用域。
        //自定义箭头函数
        let t=()=>{
            console.log(this);//打印window
        };
        t();//注意加括号

        //箭头函数作为对象方法时
        let t1={
            name:()=>{
                console.log(this);//由于对象也没有this,再次向外寻找,打印window
            }
        };
        t1.name();

        //8、显示绑定:函数通过call,apply,bind方法绑定,this指向的就是指定的对象
        function fun(){
            console.log(this.age);
        }
        var person={age:20,fun};
        var person2={age:18,fun};

        var age=28;
        fun();//28,this指向window
        person.fun();//20,指向person,此处为隐式绑定

        fun.call(person);//20,此时函数fun的this指向person,与第84行代码做对比
        fun.apply(person2);//18,此时函数fun的this指向person2
        fun.bind(person)();//20,此时函数fun的this又被绑定到了person上

        
        

    </script>
</body>
</html>

借鉴:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值