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"的关系。
相关文档:
**
* 我在网上看到过很多BASE64的JavaScript算法,都觉得不满意,于是自己写了一个,在这里分享一下。
* 我的代码在质量的效率都较高,没有一些冗余的操作。总体来讲我觉得非常不错。
* 如果大家有什么不懂的地方可以问我。
*/
var BASE64={
/**
* 此变量为编码的 ......
1.浮点运算
这可能是挫败一些对javascript不熟悉并准备执行一些数学运算的人的主要原
因.
<script>
alert(0.02 / 0.1); //0.19999999999999998
alert(1.14 * 100); //113.99999999999999 ;)
......
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 ......
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 ......