JavaScript设计模式

学习JavaScript设计模式——面向对象(二)

2019-02-28  本文已影响0人  小霸王的铲屎官

面向对象(二)

继承

1. 类式继承 将父类(第一个类)的实例赋值给第二个类的原型

    // 类式继承
    // 声明父类
    function SuperClass(){
        this.superValue = true;
    }
    // 为父类添加共有方法
    SuperClass.prototype.getSuperValue = function(){
        return this.superValue;
        
    }
    // 声明子类
    function subClass(){
        this.subValue = false
    }
    
    // 继承父类
    SubClass.prototype= new SuperClass();
    // 为子类添加共有方法
    SubClass.prototype.getSubValue = function(){
      return this.subValue;
    }

所有创建的的对象都是原生对象Object的实例

console.log(instance instanceof Object)  // true 

这种继承 如果 多个对象继承,修改父类的属性,会影响别的对象的继承属性!!!因为他们指向同一个父类的属性

 function SuperClass(){
  this.books = ['JavaScript', 'html', 'css']
 }
 
 function SubClass() {}
 SubClass.prototype = new SuperClass()
 let instance1 = new SubClass()
 let instance2 = new SubClass()
 console.log(instance2.books) // ['JavaScript', 'html', 'css']
 instance1.books.push('设计模式')
 console.log(instance2.books) // ['JavaScript', 'html', 'css', '设计模式']

2.构造函数继承——创建即继承 call or apply

// 构造函数式继承
// 声明父类
function SuperClass(id){
    // 引用类型共有属性
    this.books = ['JavaScript', 'html', 'css']
    // 值类型共有属性
    this.id = id
}
// 父类声明原型方法
SuperClass.prototype.showBooks = function(){
    console.log(this.books)
}
// 声明子类
function SubClass(id){
    // 继承父类 通过子类this 应用于 父类SuperClass 的属性和方法
    SuperClass.call(this,id)
    
}

// 创建第一个子类的实例
let instance1 = new SubClass(10)
// 创建第二个子类的实例
let instance2 = new SubClass(11)

instance1.push('设计模式')
console.log(instance1.books) // ['JavaScript', 'html', 'css', '设计模式']
console.log(instance1.id)    // 10
console.log(instance2.books) // ['JavaScript', 'html', 'css']
console.log(instance2.id)    // 11

instance1.showBooks()        // TypeError

call 和 apply 都可以继承 A.call(B, arg1,arg2) A.apply(B, argArray), 通过子类B应用于父类 A 的属性和方法

call 如果有多个属性参数,传递形式为多个参数

apply 如果有多个属性参数,传递形式为参数的数组

3. 组合继承——将优点为我所用

 // 组合式继承
 // 声明父类
 function SuperClass(name){
   // 值类型共有属性
   this.name = name
   // 引用类型共有属性
   this.books = ['html', 'css', 'JavaScript']
 }
 // 父类原型共有方法
 SuperClass.prototype.getName = function() {
    console.log(this.name)
 }
 
 // 声明子类
 function SubClass(name, time){
    // 构造函数式继承父类name属性
    SuperClass.call(this, name)
    // 子类中新增共有属性
    this.time = time 
 }
 
 // 类式继承 子类原型继承父类
 SubClass.prototype = new SuperClass()
 // 子类型原型方法
 SubClass.prototype.getTime = function() {
    console.log(this.time)
 }

测试一下

 let instance1 = new SubClass('js book', 2014)
 instance1.books.push('设计模式')
 console.log(instance1.books)  // ['html', 'css', 'JavaScript', '设计模式']
 instance1.getName()           // js book
 instance1.getTime()           // 2014
 
 let instance2 = new SubClass('css book', 2013)
 console.log(instance2.books)  // ['html', 'css', 'JavaScript']
 instance2.getName()           // css book
 instance2.getTime()           // 2013

太累了,明天再写……原型式继承

上一篇 下一篇

猜你喜欢

热点阅读