JavaScript学习(六)this指向更改

JavaScript学习(六)this指向更改

 

一、函数的调用方式决定了 this 的指向不同:

 

1.普通函数调用,此时 this 指向 window

    function fn() {
       console.log(this);   // window
     }
     fn();  //  window.fn(),此处默认省略window

 

2.构造函数调用, 此时 this 指向 实例对象

 function Person(age, name) {
         this.age = age;
         this.name = name
         console.log(this)  // 此处 this 分别指向 Person 的实例对象 p1 p2
     }
    var p1 = new Person(18, 'zs')
    var p2 = new Person(18, 'ww')

 

3.对象方法调用, 此时 this 指向 该方法所属的对象

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

 

4.通过事件绑定的方法, 此时 this 指向 绑定事件的对象

<body>
    <button id="btn">hh</button>
<script>
    var oBtn = document.getElementById("btn");
    oBtn.onclick = function() {
        console.log(this); // btn
    }
</script>
</body>

 

5.定时器函数, 此时 this 指向 window

 setInterval(function () {
       console.log(this); // window
     }, 1000);

 

 

二、更改this指向的三个方法

1.call() 方法

 

2.apply() 方法

apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是参数列表

 

3.bind()方法
bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上

 

 function fn(x, y) {
            console.log("我想你了");
            console.log(this);
            console.log(x + y);
        }
        // fn()
        var o = {
            name: 'o'
        }
        // 1.call方法 最好是实现继承
        fn.call(o, 1, 2)

        function Fn1() {
            this.showTxt = function (text) {
                console.log(text);
            }
        }

        function Fn2() {
            Fn1.call(this);
        }
        var c2 = new Fn2();
        c2.showTxt("hh");
        console.log("*************----------------------*********");

        // 2.apply方法 参数必须是数组
        function fna(arr) {
            console.log(this);
            console.log(arr);
        }
        fna.apply(o, ['pink'])
        var arr = [12, 23, 45, 13, 67, 34]
        var max = Math.max.apply(Math, arr)
        console.log(max);
        console.log("*************----------------------*********");
        // 3.bind方法  不会调用原函数 返回this值,实现原函数拷贝
        function fnb() {
            console.log(this);
        }
        var f = fnb.bind(o)
        f()

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值