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 "的关系是违背的。
相关文档:
// 调用页面的刷新方法
IHTMLWindow2* pWindow;
IHTMLDocument2* pDocument;
HRESULT hr = GetDHtmlDocument(&pDocument);
hr = pDocument->get_pa ......
第三章 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 ......
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>five-in-a-raw</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
  ......