【javascript】 function.apply 菜鸟学习笔记

今天无意看到 function有个apply的函数于是就去看看 发现很好玩 在这里分享下 先看看参数


   apply方法能劫持另外一个对象的方法,继承另外一个对象的属性

   Function.apply(obj,args)方法能接收两个参数

       obj:这个对象将代替Function类里this对象

       args:这个是数组,它将作为参数传给Function(args-->arguments)
           --args的数组就会一个个的变成那个方法的参数

 好啦 现在来看看apply的用法 

  1)使用apply来简单实现js的继承 上代码

    function Person(name){
        this.name= name,
        this.eat= function(){
            document.writeln(this.name);
        }
    }
    function child (name,age){
        Person.apply(this,arguments),
        this.age=age
    }
    child.prototype.fly= function(where){
       document.writeln(where)
    } ;


    var a = new child("pc",12);
    a.fly("  house") ;
    a.eat("sweet ")
     输 结果

   

 house pc

   class child是没有eat方法的使用apply就可以简单的实现继承

=====================分割线=============================

要注意的是Person如果使用prototype的方法不能被继承? 上代码吧

    function Person(name){
        this.name= name
    }
    Person.prototype.eat=function(food){
        document.writeln(this.name);

    } ;
    function child (name,age){
        Person.apply(this,arguments),
        this.age=age
    }
    child.prototype.fly= function(where){
       document.writeln(where);
    } ;


    var a = new child("pc",12);
    a.fly("  house") ;
    a.eat("sweet ")

运行后 只会输出 house 

   


所以使用apply来实现的时候要注意方法写在Person里面


2)使用apply的arg写出优雅的代码 如

     1.

     var a =  Math.min(1,3,7,2,8,8);
     document.writeln(a); //1

但是如果我要求出一个数组的的min呢 难道要写循环? apply 帮您解决

   

     var a = [1,3,7,2,8,8] ;


     var b=Math.min.apply(null,a)  ;
     document.writeln(b); //1


        2.  

       var arr1=[1,2,3];
       var arr2 = [4,5,6] ;
       arr1.push(arr2);
       console.log(arr1);

        这样就会出现 [1,2,3,[4,5,6]] apply也可以解决

       var arr1=[1,2,3];
       var arr2 = [4,5,6] ;
       arr1.push.apply(arr1,arr2);
       console.log(arr1);//[1,2,3,4,5,6]

               也可以这样写

       var arr1=[1,2,3];
       var arr2 = [4,5,6] ;
       Array.prototype.push.apply(arr1,arr2)
       console.log(arr1);<span style="font-family: Arial, Helvetica, sans-serif;">//[1,2,3,4,5,6]</span>


    




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值