先上代码:
apply()方法示例
/*定义一个人类*/ function Person(name,age) { this.name=name; this.age=age; } /*定义一个学生类*/ function Student(name,age,grade) { Person.apply(this,arguments); //arguments即["zhangsan", 21, "一年级"] this.grade=grade; } //创建一个学生类的实例 var student=new Student("zhangsan",21,"一年级"); //测试 console.log("name:"+student.name+" "+"age:"+student.age+" "+"grade:"+student.grade); /* 结果输出: name:zhangsan age:21 grade:一年级 */
call()方法示例-1:
/*定义一个人类*/ function Person(name,age) { this.name=name; this.age=age; } /*定义一个学生类*/ function Student(name,age,grade) { Person.call(this,name,age); this.grade=grade; } //创建一个学生类的实例 var student=new Student("zhangsan",21,"一年级"); //测试 console.log("name:"+student.name+" "+"age:"+student.age+" "+"grade:"+student.grade); /* 结果输出: name:zhangsan age:21 grade:一年级 */
call()方法示例-2:
/*定义一个人类*/ function Person(name,age) { this.name=name; this.age=age; } /*定义一个学生类*/ function Student(name,age,grade) { Person.call(this,name); this.grade=grade; } //创建一个学生类的实例 var student=new Student("zhangsan",21,"一年级"); //测试 console.log("name:"+student.name+" "+"age:"+student.age+" "+"grade:"+student.grade); /* 结果输出: name:zhangsan age:undefined grade:一年级 */