JavaScript改变this指向的三种方法

1.call() 方法 

call() 可以改变函数内的this 指向,可以调用函数

    <script>
        function Person() {
            this.name = 'kobe';
            this.sex = '男';
            this.age = '41';
        }

        function Star(name,sex,age) {
            Person.call(this,name,sex,age);  //call 改变了this指向
            console.log(this.name);
            console.log(this.sex);
            console.log(this.age);
        }
        new Star();     // 实例化对象
    </script>

2. apply() 方法

apply() 方法可以改变this指向,也会调用函数  和 call() 不同点是 apply() 的参数必须是数组或者伪数组的形式

  <script>
        function Person() {
            this.name = 'kobe';
            this.sex = '男';
            this.age = '41';
        }

        function Star(arr) {
            console.log(this); // 这个this指向 Star
            console.log(arr);
        }
        Star.apply(Person,['科比']) // 改变this指向之后,变成指向Person ,且参数要是数组形式
  </script>

3. bind() 方法

bind() 方法 可以改变this指向,但不会调用原来的函数,返回的是改变this指向之后的产生的新函数

   <script>
        function Person() {
            this.name = 'kobe';
            this.sex = '男';
            this.age = '41';
        }

        function Star(a,b) {
            console.log(this);
            console.log(a + b);
        }
        var fn = Star.bind(Person,1,3);  // 不会调用原来的函数,产生一个新的函数(this指向改变的新函数)
        fn();
   </script>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值