JavaScript的apply和call方法及其区别
参考资料:
http://blog.csdn.net/myhahaxiao/article/details/6952321
apply和call能“劫持”其他对象的方法来执行,其形参如下:
apply(obj, array parameters)
call(obj, parameter1,parameter2,...)
示例:
/*定义一个人类*/ function Person(name,age) { this.name=name; this.age=age; } /*定义一个学生类*/ function Student1(name,age,grade) { Person.apply(this,arguments); this.grade=grade; } /*定义另一个学生类*/ function Student2(name,age,grade) { Person.call(this,name,age); this.grade=grade; } //创建一个学生类 var student1=new Student1("zhangsan",8,"一年级"); var student2=new Student2("wangwu",9,"二年级");
console.log("name:"+student1.name+"\n"+"age:"+student1.age+"\n"+"grade:"+student1.grade); console.log("name:"+student2.name+"\n"+"age:"+student2.age+"\n"+"grade:"+student2.grade);