javascript继承方式之一
面向对象的语言多数都支持继承,继承最重要的优点就是代码复用,从而构建大型软件系统。如果一个类能够重用另一个类的属性和或方法,就称之为继承。
从这个角度来看看js的继承方式。js中继承方式与写类方式息息相关。不同的写类方式造成不同的继承方式。各种流行js库继承方式也各不相同。从最简单的
复用开始。
1、构造函数写类,通过方法调用复制父类属性给子类
实现继承
这里父类,子类都用构造函数方式写,不用原型。子类调用父类函数来复制父类的属性。
/**
* 父类Polygon:多边形
* @param {Object} sides
*/
function Polygon(sides) {
this.sides = sides;
this.setSides = function(s) {this.sides=s;}
}
/**
* 子类Triangle:三角形
*/
function Triangle() {
this.tempfun = Polygon;//父类引用赋值给子类的一个属性tempfun
this.tempfun(3);//调用
delete this.tempfun;//删除该属性
this.getArea = function(){};
}
//new个对象
var tri = new Triangle();
console.log(tri.sides);//继承的属性
console.log(tri.setSides);//继承的方法
console.log(tri.getArea);//自有的方法
//缺点是对于Triangle的实例对象用instanceof为父类Polygon时是false
console.log(tri instanceof Triangle);//true
console.log(tri instanceof Polygon);//false
因为js具名函数有四种调用方式
,子类还可以有以下的多种实现方式。只是在子类中调用父类方法不同而已。
function Triangle() {
Polygon.call(this,3);//call方式调用父类
this.getArea = function(){};
}
function Triangle() {
Polygon.apply(this,[3]);//apply方式调用父类
this.getArea = function(){};
}
function Triangle() {
var temp = new Polygon(3);//new方式调用父类
for(atr in temp)//全部复制给子类
this[atr] = temp[atr];
this.getArea = function(){};
}
这种方式的缺点是子类的实例对象用instanceof检查父类时总是false。这与java中继承"is a "的关系是违背的。
相关文档:
第二章:ECMAScript基础
1.当函数无明确返回值时,返回的也是值undefined
function testFunc(){}
alert(testFunc()==undefined);
2.typeof(null)=='object' //true,null可以解释为对象占位符
3.undefined 是声明了变量但未对其初始化时赋予该变量的值,null则用于表示尚未存在的对象。
alert(nu ......
Dynamic Scopes 动态作用域
Both the with statement and the catch clause of a try-catch statement, as well as a function containing eval_r(), are all considered to be dynamic scopes. A dynamic scope is one that exists only through execution of code and therefore cannot be det ......
第三章 DOM Scripting DOM编程
DOM scripting is expensive, and it's a common performance bottleneck in rich web applications. This chapter discusses the areas of DOM scripting that can have a negative effect on an application's responsiveness and gives recommendations o ......
var
xmlDoc
=
null
;
function
parseXML
(
xmlUrl
)
{
try
{
//IE
xmlDoc
=
new
ActiveXObject
(
"Microsoft.XMLDOM"
);
xmlDoc
.
async
=
false
;
xmlDoc
......