1、组合继承

组合继承带来的问题很明细就是父类的构造函数会调用两次,如:
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.color=["red","blue","green"]; }
Person.prototype.sayHello=function(){ console.log("hello word!")}; function Man(name,age,sex,job){
Person.call(this,name,age,sex);// 第二次
this.job=job;
}
Man.prototype=new Person();//第一次
var instance=new Man("张三",20,"男","农民");
instance.color.push("black");
console.log(instance.color);//["red", "blue", "green", "black"]
console.log(instance.job);//农民
console.log(instance.sayHello);//hello word! var instance2=new Man("张三",20,"男","地主");
console.log(instance2.color); //["red", "blue", "green"]
console.log(instance2.job);//地主
console.log(instance2.sayHello);//hello word!

2、寄生组合式继承

js中继承的本质是对象的内部属性_proto_ 指向原型对象,那么解决组合继承的问题其实很简单,我们只要克隆一个父类的原型对象来代替这句代码

Man.prototype=new Person();

那理论是不是也是可以的呢?

继续看代码:

//寄生组合式继承
function inheritPrototype(child,parent){
var prototype=Object(parent.prototype);// 第一步:创建一个变量接收父类原型对象
prototype.constructor=child;// 第二步:原型对象构造指向子类
child.prototype=prototype;// 第三步:用父类副本的原型对象重写子类原型对象
} //基类
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.color=["red","blue","green"];
}
Person.prototype.sayHello=function(){ console.log("hello word!")}; //子类
function Man(name,age,sex,job){
Person.call(this,name,age,sex);//继承属性
this.job=job;
} inheritPrototype(Man,Person);// 继承原型方法 var instance=new Man("张三",20,"男","农民");
instance.color.push("black");// 数组添加一个元素
console.log(instance.color);//["red", "blue", "green", "black"]
console.log(instance.job);//农民
console.log(instance.sayHello);//hello word! var instance2=new Man("张三",20,"男","地主");
console.log(instance2.color); //["red", "blue", "green"]
console.log(instance2.job);//地主
console.log(instance2.sayHello);//hello word!

事实证明这样处理是可以的。寄生组合式继承只调用一次Person 构造函数,与此同时还原型链还能保持不变;普遍认为这是最理想的继承模式了;

最新文章

  1. python中引用
  2. Visual Studio 2010 插件之Resharper
  3. ASP.NET 多语言的实现(后台消息+前台消息+页面自动绑定)
  4. hibernate建表一对多 一的一方控制多的方
  5. ZooKeeper是什么?
  6. win7 X64可用的单文件IE7 遨游美化版
  7. poj 2697 A Board Game(bfs+hash)
  8. Android内存泄漏简介
  9. redis两种持久化方法对比分析
  10. c/c++ 多线程 多个线程等待同一个线程的一次性事件
  11. 关于12c安装后打补丁
  12. es _cat API
  13. ccc切割刚体
  14. for循环的灵活性
  15. apicloud 聊天输入框模块UIChatBox
  16. MySQL笔记(二)数据库对象的创建和管理
  17. Linux进程学习 - 孤儿进程和守护进程
  18. tipask 不能正常解析
  19. hook 学习
  20. [Erlang25]Erlang in anger 翻译

热门文章

  1. jmeter同步定时器
  2. Docker学习笔记三:Docker部署Java web系统
  3. LINUX内核分析第四周——扒开系统调用的三层皮
  4. ER-18
  5. django 自己编写admin
  6. oracle 时间
  7. Codeforces Round #423 (Div. 2, rated, based on VK Cup Finals) C 并查集
  8. laravel5.1 eloquent with 通过闭包筛选特定 field 得不到结果的问题
  9. 查看git拉取地址
  10. java-压缩文件成zip文件(多文件/单文件/多目录/单目录/无目录),用于下载