JS中的call 、apply解读

一、定义

call()、apply()都是函数对象的一个方法,作用是改变函数的调用对象;
以另一个对象替换当前对象来调用该函数;
通过它们的第一个参数来指定函数的上下文;

二、语法

call([thisObj[,arg1[, arg2[, [,.argN]]]]]) 

apply([thisObj[,argArray]]) 
 
参数说明:
第一个参数(thisObj):新指定的函数对象的上下文,如果没有提供参数,默认Globle对象
第二个参数:被调用方法的传参;

三、区别

call的arg传参需要一个个传,apply则直接传一个数组。

function hello (name, age){ 

   console.log(name);

   console.log(age);

 }

 hello.call(this,"tsrot", 24); 

hello.apply(this,["tsrot",24]); 


四、运用场景

1、实现继承

function Animal(name){

      this.name = name;

      this.showName = function(){

            consloe.log(this.name);

       }

 }

 function Cat(name){

          Animal.call(this. name);// Cat继承了AnimaL的showName方法

 }

 var cat = new Cat('Black Cat'); 

cat.showName();//Black Cat 


2、数组追加

var array1 = [1, 2, 3, 5];

 car array2 = ["xie", "li", "qun", "tsrot"]; 

Array.prototype.push.aplly(array1,array2); 

console.log(array1);//[1, 2, 3, 5, "xie", "li", "qun", "tsrot"] 


3、获取数组中的最大值和最小值

var num = [1,3,5,7,2,-10,11];

 var maxNum = Math.max.apply(Math, num); 

var minNum = Math.min.apply(Math, num);

 console.log(maxNum); //11 

console.log(minNum); //-10 


4、将伪数组转换为数组

var fakeArr = {0:'a',1:'b',length:2};

 var arr1 = Array.prototype.slice.call(fakeArr); 

console.log(arr1[0]); //a

 var arr2 = [].slice.call(fakeArr);

 console.log(arr2[0]); //a 

arr1.push("c");

 console.log(arr1); //["a", "b", "c"] 


5、保存this 变量

// 正常情况下使用变量保存 this 值

 var foo = { 

     bar : 1, eventBind: function(){

           var _this = this ;

           $('.someClass').on('click',function(event) { 

                /* Act on the event */ 

               console.log(_this.bar); //1

                });

          }

 }




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值