1,call或者apply
function Teacher(name, age) {
this.name = name
this.age = age
this.sayhi = function() {
console.log('name is ' + name, 'age is' + age)
}
}
Teacher.prototype.sayAge = function() {
console.log('age is ' + this.age)
}
function Student() {
var args = arguments
Teacher.call(this, args[0], args[1])
// Teacher.apply(this, args)
}
var teacher = new Teacher('xiaoming', 23)
teacher.sayhi()
// name is xiaoming age is 23
var student = new Student('xiaolan', 12)
student.sayhi()
// name is xiaolan age is 12
注意:该继承是通过父类的call或者apply调用,只能继承定义在父类中的方法,定义在父类原型上的方法无法继承,如sayAge方法,使用student.sayAge()会报错,那么如何继承父类原型上的方法呢,请看实例2
2,原型链
function Teacher(name, age) {
this.name = name
this.age = age
}
Teacher.prototype.sayAge = function() {
console.log('age is ' + this.age)
}
function Student(age) {
this.age = age
}
Student.prototype = new Teacher()
Student.prototype.constructor = Student
var teacher = new Teacher('xiaoming', 23)
teacher.sayAge()
// age is 23
var studet = new Student('xiaolan', 12)
studet.sayAge()
// age is 12
注意,该处是通过子类原型对象继承父类的实例从而使子类的原型对象获得父类实例上的属性与方法
Student.prototype.constructor = Student这个非常重要,每个原型对象都有一个constructor属性指向该类,
Student.prototype的原型对象继承父类实例之后,Student.prototype.constructor实际上指向了Teacher,当然这里即使不指回来也并不影响运行
3,混合以上两种调用
function Teacher(name, age) {
this.name = name
this.age = age
}
Teacher.prototype.sayAge = function() {
console.log('age is ' + this.age)
}
function Student() {
var args = arguments
Teacher.call(this, args[0], args[1])
// Teacher.apply(this, args)
}
Student.prototype = new Teacher()
Student.prototype.constructor = Student
var studet = new Student('xiaolan', 12)
studet.sayAge()
// age is 12
4,对象冒充
function Teacher(name, age) {
this.name = name
this.age = age
this.sayhi = function() {
console.log('name is ' + name, 'age is ' + age)
}
}
function Student(name, age) {
this.student = Teacher
this.student(name,age)
delete this.student
}
var student = new Student('xiaolan', 12)
student.sayhi()
// name is xiaolan age is 12
注意:该继承无法继承定义在父类原型对象上的方法