1、封装
写道
function extend(parent,child){
var F = function(){};
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = child;
child.uber = parent.prototype;
}
2、复制属性
写道
function extend2(parent,child){
var p = parent.prototype;
var c = child.prototype;
for(var i in p){
c[i] = p[i];
}
c.uber = p;
}
结果:
写道
function shape(){};
shape.prototype.name = 'shape';
shape.prototype.toString = function(){return this.name;}
function Triangle(){}
extend(shape,Triangle);
var s = new Triangle();
s.toString();// "shape"
s.name;// "shape"
extend2(shape,Triangle);
var t = new Triangle();
t.name;//"shape"
3、多继承的实现
function multi() {
var n = {}, stuff, j = 0, len = arguments.length;
for (j = 0; j < len; j++) {
stuff = arguments[j];
for (var i in stuff) {
n[i] = stuff[i];
}
}
return n;
}
var shape = {
name: 'shape',
toString: function() {return this.name;}
};
var twoDee = {
name: '2D shape',
dimensions: 2
};
var triangle = multi(shape, twoDee, {
name: 'Triangle',
getArea: function(){return this.side * this.height / 2;},
side: 5,
height: 10
});
>>> triangle.getArea();//25 >>> triangle.dimensions;// 2 >>> triangle.toString();//"Triangle"
本文介绍了JavaScript中实现封装和继承的方法,包括单继承和多继承的实现方式,并通过具体示例展示了如何使用自定义函数extend和extend2进行类的扩展。
3016

被折叠的 条评论
为什么被折叠?



