zoukankan      html  css  js  c++  java
  • js中call、apply、bind的区别和应用

    一、总体概述

      这三个方法都是改变函数本身的this指向的,但是略有不同

    1、call

      使用方法:函数名.call(this指向,展开的参数列表);

      如果传入的this指向是null或者是undifined,那么this的指向将会是window

      

     //call的应用
            //这里的obj称之为类数组,类似于数组,实际上就是一个对象
            var obj = {
                0:10,
                1:20,
                2:29,
                3:77,
                length:4
            }
            //我们在数组的原型上加上加和的方法
            Array.prototype.getSum = function () {
                var res = 0;
                for(var i = 0;i<this.length;i++){
                    res += this[i];
                }
                return res;
            }
            //下面我们来确定如何使用数组上的这个加和方法
            // //1、改变this指向
            // var res = Array.prototype.getSum.call(obj);
            // console.log(res);
            //2、把类数组先转化成数组
            var arr = Array.prototype.splice.call(obj,0,4);
            var res = arr.getSum();
            console.log(res);

    2、apply和call类似,只不过call传递的是展开的参数列表,而apply传递的是数组的参数列表

            //apply的应用
            // 计算arr中的最大值,考虑到Math.max()可以实现,但是传递的参数只能是展开的参数列表
            var arr = [11,12,35,66,99,45,44,2];
            //方式一:es6的参数展开
            var res = Math.max(...arr);
            console.log(res);
            //方式二:使用apply
            var res2 = Math.max.apply(null,arr);
            console.log(res2);

    3、bind的应用并非马上执行,而是调用返回值加小括号时才会执行。

      //bind的应用
            var obj = {
                name:"zs",
                fn:function () {
                    setInterval(function () {
                    console.log(this.name);
                    },200)
                },
                fn2:function(){
                    setInterval(function () {
                    console.log(this.name);
                    }.bind(this),200)
                }   
            }
            obj.fn();
            obj.fn2();
  • 相关阅读:
    暑假训练第三周总结
    UVA 1212 Duopoly
    UVA 12125 March of the Penguins
    UVA 1345 Jamie's Contact Groups
    UVA 10806 Dijkstra, Dijkstra.
    暑假训练第一周总结
    HDU 5792 World is Exploding
    HDU 5791 Two
    HDU 5787 K-wolf Number
    Sql With as 用法
  • 原文地址:https://www.cnblogs.com/dhrwawa/p/10508453.html
Copyright © 2011-2022 走看看