zoukankan      html  css  js  c++  java
  • call 和 apply的使用

    call

      /**
         * 改变this指向
         * */
        function People(){
            this.name = "--";
            this.age = 0;
            this.show = function(){
                console.log(this.name,'今年',this.age,"岁");
            }
        }
        function Man(name, age){
            this.name = name;
            this.age = age;
        }
        var people = new People();
        var man = new Man("小明",25);
        people.show(); // -- 今年 0 岁
        people.show.call(man); //小明 今年 25 岁
       /**
         * 继承
         * */
        function People(name){
            this.name = name;
            this.showName = function(){
                console.log(this.name);
            }
        }
        function Man(name,song){
            //继承 People
            this.song = song;
            People.call(this,name);
        }
        // 自己的特长(原型方法)
        Man.prototype.sing = function(){
            console.log("爱唱",this.song);
        }
        var man = new Man("朱元璋","光辉岁月");
        man.showName(); //朱元璋
        man.sing();// 爱唱 光辉岁月

    apply

       /**
         * 改变this指向
         * */
        function People(){
            this.name = "--";
            this.age = 0;
            this.show = function(){
                console.log(this.name,'今年',this.age,"岁");
            }
        }
        function Man(name, age){
            this.name = name;
            this.age = age;
        }
        var people = new People();
        var man = new Man("小明",25);
        people.show(); // -- 今年 0 岁
        people.show.apply(man); //小明 今年 25 岁
        /**
         * 继承
         * */
        function People(name){
            this.name = name;
            this.showName = function(){
                console.log(this.name);
            }
        }
        function Man(name,song){
            //继承 People
            this.song = song;
            People.apply(this,[name]);//注意区别
        }
        // 自己的特长(原型方法)
        Man.prototype.sing = function(){
            console.log("爱唱",this.song);
        }
        var man = new Man("朱元璋","光辉岁月");
        man.showName(); //朱元璋
        man.sing();// 爱唱 光辉岁月

    两者之间的却别

    1、call是多个参数,apply是两个参数(第二个参数数组的方式传递)

    a.call(b,arg1,arg2…)
    
    apply(b,[arg1,arg2]) //apply只有2个参数,它将call的参数(arg1,arg2…)放在一个数组中作为apply的第二参数

    2、对一些对象方法的调用,比如数组的forEach的调用

     call的方法

    [].forEach.call('1,2,3',function(item){console.log(item)}); // 1,2,3

    apply同样使用会报错

    [].forEach.call('1,2,3',function(item){console.log(item)}); // VM777:1 Uncaught TypeError: undefined is not a function(…)
  • 相关阅读:
    hdu6007 Mr. Panda and Crystal 最短路+完全背包
    ID生成器的一种可扩展实现方案
    使用PUT方法上传文件无法工作原因分析
    负载均衡算法
    父类和子类属性覆盖的各种情况分析
    java functional syntax overview
    Starter Set of Functional Interfaces
    application/xml和text/xml的区别
    mime type 概要介绍
    spring mvc 详细执行流程
  • 原文地址:https://www.cnblogs.com/xianglx/p/5677052.html
Copyright © 2011-2022 走看看