继承

什么是继承

  • 现实生活中的继承
  • 程序中的继承

构造函数的属性继承:借用构造函数

  1. function Person (name, age) {
  2. this.type = 'human'
  3. this.name = name
  4. this.age = age
  5. }
  6. function Student (name, age) {
  7. // 借用构造函数继承属性成员
  8. Person.call(this, name, age)
  9. }
  10. var s1 = Student('张三', 18)
  11. console.log(s1.type, s1.name, s1.age) // => human 张三 18

构造函数的原型方法继承:拷贝继承(for-in)

  1. function Person (name, age) {
  2. this.type = 'human'
  3. this.name = name
  4. this.age = age
  5. }
  6. Person.prototype.sayName = function () {
  7. console.log('hello ' + this.name)
  8. }
  9. function Student (name, age) {
  10. Person.call(this, name, age)
  11. }
  12. // 原型对象拷贝继承原型对象成员
  13. for(var key in Person.prototype) {
  14. Student.prototype[key] = Person.prototype[key]
  15. }
  16. var s1 = Student('张三', 18)
  17. s1.sayName() // => hello 张三

另一种继承方式:原型继承

  1. function Person (name, age) {
  2. this.type = 'human'
  3. this.name = name
  4. this.age = age
  5. }
  6. Person.prototype.sayName = function () {
  7. console.log('hello ' + this.name)
  8. }
  9. function Student (name, age) {
  10. Person.call(this, name, age)
  11. }
  12. // 利用原型的特性实现继承
  13. Student.prototype = new Person()
  14. var s1 = Student('张三', 18)
  15. console.log(s1.type) // => human
  16. s1.sayName() // => hello 张三