面向对象中继承实现

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

注意:该继承无法继承定义在父类原型对象上的方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值