javascript继承方式之三
3、组合构造函数/原型方式写类,采用前面种方式继承
这种方式父类,子类的属性都挂在构造函数里,方法都挂在原型上。
/**
* 父类Polygon:多边形
*/
function Polygon(sides) {
this.sides = sides;
}
Polygon.prototype.setSides = function(s) {this.sides=s;}
/**
* Triangle 三角形
* @param {Object} base 底
* @param {Object} height 高
*/
function Triangle(base,height) {
Polygon.call(this,3);//复制父类属性给自己
this.base = base;
this.height = height;
}
Triangle.prototype = new Polygon();//复制父类方法给自己
Triangle.prototype.getArea = function(){ //最后定义自己的方法
return this.base*this.height/2;
}
//new个对象
var tri = new Triangle(12,4);
console.log(tri.sides);//继承的属性
console.log(tri.setSides);//继承的方法
console.log(tri.base);//自有属性
console.log(tri.height);//自有属性
console.log(tri.getArea);//自有方法
//instanceof测试,表明正确的维护了"is a"的关系
console.log(tri instanceof Triangle);//true,表明该对象是三角形
console.log(tri instanceof Polygon);//true,表明三角形也是多边形
嗯。按照这种模式写js,也能构建一些大型模块。
相关文档:
功能:
重新加载文档。
语法:
location.reload(force)
参数:
force:可选参数,是一个布尔值。
如果省略参数,或者参数是false,它就会用HTTP头If-Modified-Since来检测服务器上的文档是否已改变。如果文档已改
变,reload()会再次下载该文档。如果文档未改变,则该方法将从缓存中 ......
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 ......
Nested Members 嵌套成员
Since object members may contain other members, it's not uncommon to see patterns such as window.location.href in JavaScript code. These nested members cause the JavaScript engine to go through the object member resolution process each time a dot is ......
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 ......
2、原型方式写类,原型方式继承
core js自身的对象系统就是采用原型方式(prototype based)继承的。或者说core
js没有采用常见的类继承(class
based)系统,而是使用原型继承来实现自己的对象系统。工作中我们也可以用原型方式来实现继承,代码复用以构建自己的功能模块。
/**
* 父类Polygon:多边形
*
*/
functio ......