javascript笔记---改变函数内部this指向call(),apply(),bind()方法

call()

call() 方法调用一个对象。简单理解为调用函数的方式,但是它可以改变函数的 this 指向。
fun.call(thisArg, arg1, arg2, ...)

1,thisArg:在 fun 函数运行时指定的 this 值
2,arg1,arg2:传递的其他参数
3, 返回值就是函数的返回值,因为它就是调用函数
4, 因此当我们想改变 this 指向,同时想调用这个函数的时候,可以使用 call,比如继承

var o = {
            name: "andy",
        }
        function fn(a, b) {
            // this.name=name;
            console.log(this);
            console.log(a + b);
        }
        // call第一可以调用函数,也可以改变函数的this指向
        //将fn函数中的this指向o这个对象,
        fn.call(o, 1, 2);

输出:Objectname: "andy"__proto__: Objectcall(),apply(),bind()方法.html:56 3

call来继承

   function Father(name, id) {
            this.name = name;
            this.id = id;
        }
        function Son(name, id) {
            // 这里是this指向Son,所以意思是将Fathe的this指向改成指向Son的
            Father.call(this, name, id)
        }
        var son = new Son("刘德华", 18);
        console.log(son);

输出:在这里插入图片描述

apply()

fun.apply(thisArg, [argsArray])

1, thisArg:在fun函数运行时指定的 this 值
2,argsArray:传递的值,必须包含在数组里面
3,返回值就是函数的返回值,因为它就是调用函数
4,因此 apply 主要跟数组有关系,比如使用 Math.max() 求数组的最大值

 var e = {
            id: 2,
        }
        function fathe() {
            console.log(this);
        }
        //apply可以直接调用函数,也可以改变函数里面this的指向
        fathe.apply();
        fathe.apply(e);

输出:在这里插入图片描述

apply()通过内置数学函数对象求最大值

var ar = [2, 98, 20, 53];
        console.log(Math.max.apply(Math, ar));
        console.log(Math.min.apply(Math, ar));
        console.log(Math.max(...ar));
        console.log(Math.min(...ar));

输出:在这里插入图片描述

bind()

fun.bind(thisArg, arg1, arg2, ...

1,thisArg:在 fun 函数运行时指定的 this 值
2,arg1,arg2:传递的其他参数
3,返回由指定的 this 值和初始化参数改造的原函数拷贝
4,因此当我们只是想改变 this 指向,并且不想调用这个函数的时候,可以使用 bind

var ab={
            name:"andy",
        }
        function fn(a,b){
            console.log(this);
            console.log(a+b);
        }
        //bind不会直接调用函数,而是返回一个改变了this的新函数
       var f= fn.bind(ab,2,3);
       f();

输出:在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值