1.不支持继承
可以通过引入外部库来实现,zInherit.js(http://www.nczonline.net/downloads/)或者xbObjects.js(http://archive.bclary.com/xbProjects-docs/xbObject/).
通过亲身实践,总结如下:
a. zInherit库很小,只有两个方法。可以支持多重继承、instanceOf()方法、动态原型,但是不支持在子类中调用父类方法(!!!).
用法示例:
function Animal(){
if(typeof Dog._initialized == "undefined"){
Dog._initialized = true;
}
}
function Dog (name){
Animal.call(this);
Dog.inheritFrome(Animal);
if(typeof Dog._initialized == "undefined"){
Dog.prototype.init = function(name){
this.name = name;
}
Dog._initialized = true;
}
this.init(name);
}
b.xbObjects也不大,但是使用起来比zInherit麻烦。而且父类必须在子类之前注册。支持在子类中调用父类方法。
示例用法如下:
window.onload = function(){
var zy = new People();
zy.say();
}
_classes.registerClass("Animal");
function Animal(){
_classes.defineClass("Animal",prototypeFunction);
this.init();
function prototypeFunction () {
Animal.prototype.say = function(){
alert("i am animal");
this.name = "xxoo";
}
Animal.prototype.getKind = function(){
return this.kind;
}
Animal.prototype.printKind = function(){
alert(this.kind);
}
Animal.prototype.init = function(){
this.kind = "animal";
}
}
}
_classes.registerClass("People");
function People(){
_classes.defineClass("People",prototypeFunction);
this.init();
function prototypeFunction () {
People.prototype.say = function(){
alert("zy say:i am zy");
this.inner.say();
}
People.prototype.getInner = function(){
return this.inner;
}
People.prototype.init = function(){
this.height = 5 ;
this.inner = new Inner(this);
}
}
}
_classes.registerClass("Inner","Animal");
function Inner(outer){
_classes.defineClass("Inner",prototypeFunction);
this.init();
function prototypeFunction () {
Inner.prototype.say = function(){
var string="inner say: 'i am "+this.name+" , i am a kind of "+ this.getKind()+". my height is "+ this.outer.height;
alert(string);
}
Inner.prototype.init = function(){
this.parentMethod("init");
this.outer = outer;
this.name = "tiger"
}
}
}
2.不支持函数重载
只能模拟实现,由于js对函数接收的参数个数不限制,所以,可以通过根据对实际接收到的参数的个数来进行不同操作。
示例:
Figure.prototype.repaint = function(){
var x;
var y;
var width;
var height;
if(arguments.length == 0){
x = this.bounds.x;
y = this.bounds.y;
width = this.bounds.width;
height = this.bounds.height;
}else if(arguments.length == 1){
var rect = arguments[0];
x = rect.x;
y = rect.y;
width = rect.width;
height = rect.height;
}else if(arguments.length == 4){
x = arguments[0];
y = arguments[1];
width = arguments[2];
height = arguments[3];
}
if (this.isVisible())
this.getUpdateManager().addDirtyRegion(this, x, y,width, height);
}
3.关联数组的键不能为一个自定义对象,所以不能通过此方法来实现Map。