易截截图软件、单文件、免安装、纯绿色、仅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学习笔记(六)

1.DOM是针对XML的基于树的API。使用DOM,只需解析代码一次来创建一个树的模型。在这个初始解析过程之后,XML已经完全通过DOM模型表现出来,同时也不再需要原始的代码。
   NB
:DOM是语言无关的API,它并不与Java、JavaScript或其他语言绑定。 ......

[翻译]High Performance JavaScript(006)

Identifier Resolution Performance  标识符识别性能
    Identifier resolution isn't free, as in fact no computer operation really is without some sort of performance overhead. The deeper into the execution context's scope chain an identifier exists, the slower it is to access for ......

[翻译]High Performance JavaScript(007)

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 ......

[翻译]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 ......

自己写的javascript五子棋

<!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>
  ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号