您的当前位置:首页JavaScript 继承 封装 多态实现及原理详解

JavaScript 继承 封装 多态实现及原理详解

2020-11-27 来源:乌哈旅游

var parent = function(name,age){
 this.name = name;
 this.age = age;
}
 
parent.prototype.showProper = function(){
 console.log(this.name+":"+this.age);
}
 
var child = function(name,age){
 parent.call(this,name,age);
}
 
// inheritance
child.prototype = Object.create(parent.prototype);
// child.prototype = new parent();
child.prototype.constructor = child;
 
// rewrite function
child.prototype.showProper = function(){
 console.log('I am '+this.name+":"+this.age);
}

var obj = new child('wozien','22');
obj.showProper();

上面这段代码通过使用寄生组合继承,实现子类私有继承父类私有,子类公有继承父类公有,达到重写父类的showProper

面向对象的5大原则

  • 单一职责原则
  • 开放封闭原则
  • 替换原则
  • 依赖原则
  • 接口分离原则
  • 单一职责原则

    单一职责原则就是我们说的一个方法只做一件事,就比如现在的项目结构,就遵循了单一职责原则

    开放封闭原则

    开放封闭原则就是对修改关闭,对扩展开放

    class a {
     add(){
     return 11
     }
     }
     class b extends a{
     
     }
     let c = new b()
     console.log(c.add()) // 111

    我们可以使用extends继承父类,可以再b里面修改add函数,实现对修改关闭,对扩展开放

    显示全文