易截截图软件、单文件、免安装、纯绿色、仅160KB

javascript继承方式之二

2、原型方式写类,原型方式继承
core js自身的对象系统就是采用原型方式(prototype based)继承的。或者说core
js没有采用常见的类继承(class
based)系统,而是使用原型继承来实现自己的对象系统。工作中我们也可以用原型方式来实现继承,代码复用以构建自己的功能模块。
/**
* 父类Polygon:多边形
*
*/
function Polygon() {}
Polygon.prototype.sides = 0;
Polygon.prototype.setSides = function(s) {this.sides=s;}
/**
* 子类Triangle:三角形
*/
function Triangle() {}
Triangle.prototype = new Polygon();//关键一句
Triangle.prototype.getArea = function(){}
//new个对象
var tri = new Triangle();
console.log(tri.sides);//继承的属性
console.log(tri.setSides);//继承的方法
console.log(tri.getArea);//自有方法
//instanceof测试
console.log(tri instanceof Triangle);//true,表明该对象是三角形
console.log(tri instanceof Polygon);//true,表明三角形也是多边形

虽然从输出可以看出子类继承了父类Polygon的属性sides和方法setSides,但sides是0,怎么会是三角形呢。还得调用下
tri.setSides(3)使之成为三角形。这样似乎很不方便。不能传参数,即是原型方式的缺点。优点是正确的维护了"is a"的关系。


相关文档:

通过javascript获得url参数

页面提交数据一般有两种方法:get,post。post就是所谓的form提交,使用视图;get是通过url提交。
Get方法一般用后台代码(如asp,asp.net)获得参数,代码很简单:Request.QueryString["id"];即可获取。 
有些时候需要直接在前台获取url参数,要用到javascript,js没有直接获取url参数的方法,那么,我们如何通过js ......

firefox与IE对javascript和CSS的区别

1. document.formName.item("itemName") 问题
说明:IE下,可以使用document.formName.item("itemName")或document.formName.elements["elementName"];
Firefox下,只能使用document.formName.elements["elementName"].
解决方法:统一使用document.formName.elements["elementName"].
2.集合类对象问题
说明:IE下,可 ......

[翻译]High Performance JavaScript(009)

第三章  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 ......

[翻译]High Performance JavaScript(010)

Cloning Nodes  节点克隆
    Another way of updating page contents using DOM methods is to clone existing DOM elements instead of creating new ones—in other words, using element.cloneNode() (where element is an existing node) instead of document.createElement().
 &nbs ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号