面向对象三大特性:封装、继承、多态。在熟悉了Java/C#/C++这些高级面向对象语言的语法结构后,我们或多或少会对javascript脚本语言的面向对象感到一些不适,function、prototype、call、apply……
为了消除这种对javascript面向对象语法的不适,众多js库都构建了更符合传统OO编程思想的代码框架,如prototype、mootools等等,引用mootools文档中创建对象的例子
| 以下是引用片段: var Animal = new Class({ initialize: function(age){ this.age = age; } }); var Cat = Animal.extend({ initialize: function(name, age){ this.parent(age); //将调用Animal的initialize方法; this.name = name; } }); var myCat = new Cat('Micia', 20); alert(myCat.name); //显示 'Micia' alert(myCat.age); //显示 20 |
| 以下是引用片段: dojo.declare("my.classes.bar", my.classes.foo, { // properties to be added to the class prototype someValue: 2, // initialization function constructor: function(){ this.myComplicatedObject = new ReallyComplicatedObject(); }, // other functions someMethod: function(){ doStuff(); } ); |
| 以下是引用片段: dojo.declare("Apple", null, { price: 5, constructor: function(weight) { this.total = weight * this.price; }, print: function() { alert("The total price is " + this.total); } } ); var myapple = new Apple(10); myapple.print(); //输出结果:"The total price is 50" |
注意dojo.declare第二个参数,如果创建一个独立的新对象,可以设为null,当需要从其他一个或多个对象继承时,则为对象名称,这样就方便的实现了对象继承。多个对象继承,declare第二个参数为一数组,第一个元素为原型父对象,其他的为mixin对象,通过代码来理解。
dojo.declare("Apple", null, {
price : 5,
constructor : function(weight) {
this.total = weight * this.price;
},
// constructor : function() {
// alert("Create Apple !");
// },
print : function() {
alert("The total price is " + this.total);
}
});
dojo.declare("AppleTree", null, {
constructor : function() {
alert("Create AppleTree !");
},
print : function() {
alert("This is an apple tree");
},
additional : function() {
alert("This is a mixin class");
}
});
dojo.declare("GreenApple", [Apple, AppleTree], {
constructor : function() {
alert("Getting a green apple");
}
});
创建一个GreenApple对象,测试alert执行顺序!mixin对象的方法将覆盖之前对象中的同名函数,除非子对象也声明了同名函数print。
| 以下是引用片段: //输出 //"The height of the tree is undefined" //"Getting a green apple" var gapple = new GreenApple(); //输出,覆盖了Apple对象的print //"This is an apple tree" gapple.print(); //"This is a mixin class" gapple.additional(); dojo/_base/_loader/bootstrap.js有专门的mixin函数,用于对象的拷贝,将一个创建好的对象拷贝到新的对象中 var copy = dojo.mixin({}, new Apple(2)); copy.print(); |
通过declare、mixin、extend,dojo给我们提供了一种方便的对象创建与扩展机制,一般情况下够用了,感觉还是比较方便,使用时也存在一些限制,翻翻源代码就能理解。这里主要是要知道dojo是如何面向对象的,方便我们更好的理解dojo基础功能,及dijit和 dojox,dojo最为强大还是它的widgets。本文涉及的js源码:
mixin:dojo/_base/_loader/bootstrap.js
extend:dojo/_base/lang.js
declare:dojo/_base/declare.js