1.定义子类:
Function.prototype.extend = function(constructor, method, statics) {
return defineSubclass(this, constructor, method, statics);
};
//复制属性(覆盖同名),不处理setter getter
function extend(o, p) {
for (prop in p) {
o[prop] = p[prop];
}
return o;
}
function inherit(p) {
if (p == null)
throw TypeError();
if (Object.create)
return Object.create(p);
//兼容
var t = typeof p;
if (t !== "object" && t !== "function")
throw TypeError();
function f() {
};
f.prototype = p;
return new f();
}
function defineSubclass(superclass, constructor, method, statics) {
constructor.prototype = inherit(superclass.prototype);
constructor.prototype.constructor = constructor;
//复制方法和类属性
if (method)
extend(constructor.prototype, method);
if (statics)
extend(constructor, statics);
return constructor;
}
//定义构造函数
function ClassA(paramA, paramB) {
//定义实例字段
this.propA = paramA;
this.getParamB = function() {
return paramB;
};
this.setParamB = function(value) {
paramB = value;
};
}
//定义实例方法
ClassA.prototype.funcA = function() {
this.setParamB(123);
return this.getParamB();
};
//定义类字段(常亮)
ClassA.STATIC_CONSTA = 1000;
//定义类方法
ClassA.staticFuncA = function() {
};
//定义类字段
ClassA._privateProp = 1;
var ClassB = ClassA.extend(function ClassB(paramA, paramB, paramC) {
//super父级构造函数
ClassA.apply(this, arguments);
this.porpC = paramC;
}, {
funcB: function (){return " this is funcB";},
//覆盖函数并调用父级同名函数
funcA: function () {
return "this is funcA's result in ClassB: " + ClassA.prototype.funcA.apply(this, arguments);
}
});