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