ECMAScript中描述了原型链的概念,原型链是实现继承的主要方法。

实现原型链继承有一种基本模式

function SuperType () {
this.property = true;
} SuperType.prototype.getSuperValue = function () {
return this.property;
}; function SubType () {
this.subproperty = false;
}
//继承SuperType
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.getSubValue =function () {
return this.subproperty;
}; var instance = new SubType();
console.log(instance.getSuperValue()); //true
console.log(instance.getSubValue()); //false

原型链虽然可以实现继承,但是在对现有的原型进行修改时,原先的原型也会被修改。这也是原型链的问题。

构造函数

使用call或apply方法

function SuperType (name) {
this.name = name;
}
function SubType () {
//继承
SuperType.call(this, "Argu");
} var instance = new SubType();
console.log(instance.name);

在考虑到原型链和构造函数实现继承时的一些问题,用的比较多的是两种方式的组合形式

组合继承

function SuperMan (name) {
this.name = name;
this.friends = ["Bob","Angular","Y"];
} SuperMan.prototype.sayName = function () {
alert(this.name);
};
function SubMan (name, age) {
SuperMan.call(this, name); this.age = age;
}
SubMan.prototype = new SuperMan();
SubMan.prototype.constructor = SubMan;
SubMan.prototype.sayAge = function () {
alert(this.age);
};
var test1 =new SubMan("Nicur", "11");
test1.friends.push("Syze");
console.log(test1.friends);            //["Bob", "Angular", "Y", "Syze"]
test1.sayName();                  //Nicur
test1.sayAge();                   //11 var test2 =new SubMan("Gina", "18");      
console.log(test2.friends);            //["Bob", "Angular", "Y"]
test2.sayName();                  //Gina
test2.sayAge(); //18

最新文章

  1. Gradle Maven 依赖管理
  2. Gridview样式的CSS控制
  3. Docker Registry搭建私有仓库
  4. [MetaHook] GameUI hook
  5. 2010-2014总结 ____V_V____ hello-world
  6. hdu 5459 Jesus Is Here 数学
  7. OpenWebFlow0.9用户手册与设计说明
  8. Linux Shell编程(7)——变量赋值
  9. HDU 2157 - How many ways??
  10. 报错:loaded the "" nib but didn't get a UITableView
  11. sqlserver 注释提取工具
  12. 全局变量引起的BUG
  13. webstorm下的sass自动编译和移动端自适应实践
  14. 感受野RF的计算
  15. 前端 - jsonp 跨域ajax
  16. 设计模式【PHP案例】
  17. NumPy 迭代数组
  18. multiprocessing、threading、gevent区别
  19. Android逆向——smali复杂类解析
  20. python之路----面向对象进阶二

热门文章

  1. jar文件运行打断点
  2. Java IO6 :IO总结
  3. 我的第一个QML Button的实现
  4. 13年山东省赛 The number of steps(概率dp水题)
  5. 巧用Graphviz和pvtrace等工具可视化C函数调用
  6. Qt中一些常用的格式转换
  7. Linux系统编程(16)——正则表达式入门
  8. bzoj1632 [Usaco2007 Feb]Lilypad Pond
  9. 【转】使用 udev 高效、动态地管理 Linux 设备文件
  10. JsonKit 解析