您的位置:首页 > 移动开发

js中apply和call方法的应用

2016-01-26 15:28 393 查看
对象的继承,就是:Function.apply(当然使用Function.call也是可以的)
apply方法能劫持另外一个对象的方法,继承另外一个对象的属性
Function.apply(obj,args)方法能接收两个参数
obj:这个对象将代替Function类里this对象
args:这个是数组,它将作为参数传给Function(args-->arguments)
apply示范代码如下:

 <script>

function Person(name,age){   //定义一个类,人类

    this.name=name;     //名字

    this.age=age;       //年龄

    this.sayhello=function(){alert("hello")};

}

function Print(){            //显示类的属性

    this.funcName="Print";

    this.show=function(){

        var msg=[];

        for(var key in this){

            if(typeof(this[key])!="function"){

                msg.push([key,":",this[key]].join(""));

            }

        }

        alert(msg.join(" "));

    };

}

function Student(name,age,grade,school){    //学生类

     console.log(typeof arguments);

    Person.apply(this,arguments);

    Print.apply(this,arguments);

    this.grade=grade;                //年级

    this.school=school;                 //学校

}

var p1=new Person("jake",10);

p1.sayhello();                                  //  hello

var s1=new Student("tom",13,6,"清华小学");

s1.show();                                   //   name:tom age:13 funcName:Print grade:6 school:清华小学

s1.sayhello();                               // helo  

alert(s1.funcName);                          // Print 

</script>

总结: a.apply(b,["zhou","23"]) // b继承a
       a.call(b,arg1,arg2);  // b继承a 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息