1. 程式人生 > >JS call與apply

JS call與apply

在實際中call主要實現的傳遞物件和繼承的功能

  //實現繼承
        function people(name,age,like){
            this.name = name;
            this.sex = "";
            this.age = age;
            this.like = like;
            this.showInfo = function(){
                console.log("我叫"+this.name+"今年"+this.age+"性別"+this.sex+"愛好"+this.like);
            }
            ;        }
        function boy(name,age,like){
            people.call(this,name,age,like);
            this.sex = "男";
        }
        function girl(name,age,like){
            people.call(this,name,age,like);
            this.sex = "女";
        }
        var boy = new boy("張明",23,"足球");
        var girl = new girl("李雪",22,"購物");
        boy.showInfo();
        girl.showInfo();

//傳遞物件
        function people(){
            this.name = "姓名";
            this.age = 23;
            this.sex = "男";
            this.like = "玩";
            this.showInfo = function(){
              console.log("我叫"+this.name+"今年"+this.age+"性別"+this.sex+"愛好"+this.like);
            }
;        }
        function boy(name,age,like){
            this.name = name;
            this.age = age;
            this.sex = "男";
            this.like = like;
        }
        function girl(name,age,like){
            this.name = name;
            this.age = age;
            this.sex = "女";
            this.like = like;
        }
        var p = new people();
        var boy = new boy("張明",23,"足球");
        var girl = new girl("李雪",22,"購物");
        p.showInfo.call(boy);
        p.showInfo.call(girl);

apply在用法上和call相似,區別在於apply傳遞引數的傳遞兩個引數(apply(this,[param[0],param[1])),call的傳參方式是call(obj,param[0],param[1],param[2])。
     //apply的用法
        function people(name,age,like){
            this.name = name;
            this.sex = "";
            this.age = age;
            this.like = like;
            this.showInfo = function(){
                console.log("我叫"+this.name+"今年"+this.age+"性別"+this.sex+"愛好"+this.like);
            }
            ;        }
        function boy(name,age,like){
            people.apply(this,[name,age,like]);
            this.sex = "男";
        }
        function girl(name,age,like){
            people.apply(this,[name,age,like]);
            this.sex = "女";
        }
        var boy = new boy("張明",23,"足球");
        var girl = new girl("李雪",22,"購物");
        boy.showInfo();
        girl.showInfo();