Javascript是面向对象的语言,但遗憾的是没有提供现成的类模型。不过没关系,广泛使用的语言总能涌现出优美的诗句。下面就是实现Javascript类模型的三部曲:
1、属性扩展
GlobalNamespace.extend = function(to, from) {
to = to || {};
if (from) {
for (var property in from) {
var value = from[property];
if (value !== undefined) {
to[property] = value;
}
}
}
return to;
};
2、属性继承
GlobalNamespace.inherit = function(Child, Parent) {
var F = function() {};
F.prototype = Parent.prototype;
Child.prototype = new F;
var i, l, o;
for(i=2, l=arguments.length; i<l; i++) {
o = arguments[i];
if(typeof o === "function") {
o = o.prototype;
}
GlobalNamespace.extend(Child.prototype, o);
}
};
3、基类工厂
GlobalNamespace.Class = function() {
var len = arguments.length;
var Parent = arguments[0];
var Proto = arguments[len-1];
var Child = typeof Proto.initialize == "function" ?
Proto.initialize :
function(){ Parent.apply(this, arguments); };
if (len > 1) {
var newArgs = [Child, Parent].concat(
Array.prototype.slice.call(arguments).slice(1, len-1),
Proto
);
GlobalNamespace.inherit.apply(null, newArgs);
} else {
Child.prototype = Proto;
}
return Child;
};
其中initialize是类的构造函数。
如此这般即可建立Javascript的类模型,例如:
定义基类
GlobalNamespace.BaseClass = GlobalNamespace.Class({
property: null,
initialize: function(p) {
this.property = p || 'property';
},
getProperty: function() {
return this.property;
}
});
定义派生类
GlobalNamespace.SubClass = GlobalNamespace.Class({
setProperty: function(p) {
this.property = p || this.property;
}
});
创建实例
var base = new GlobalNamespace.BaseClass('abc');
console.log(base.getProperty()); // 'abc'
var sub = new GlobalNamespace.SubClass('opq');
console.log(sub.getProperty()); // 'opq'
sub.setProperty('xyz');
console.log(sub.getProperty()); // 'xyz'
参考文献:
【1】JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc., 978-0-596-51774-8
【2】http://trac.osgeo.org/openlayers/browser/trunk/openlayers/lib/OpenLayers/BaseTypes/Class.js