JS call与apply

来源:互联网 发布:视频后期特效软件 编辑:程序博客网 时间:2024/05/20 16:36

在实际中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();



0 0