在javascript中实现分部类定义

    在定义类时,如果这个类足够的大,为了方便管理,会把类定义在不同的文件,但是在javascript中没有这样的功能,为了简化工作做了一个可以实现分部类定义的功能.

    其实现原理主要是通过修改原型链和call.

    代码如下:

    

 1 /*
 2 实现分部类定义
 3 
 4 定义时,如果prototype(及方法)名称以(__)开头的话,将视为临时方法,及只在初始化进行执行,后续不在需要,在执行完成后会删除此方法,
 5 目的是为了减小instance,因此在定义私有prototype(方法)时,请用(_)开头
 6 
 7 
 8 
 9 Example:
10 function animal() {
11     this.weight = 100;
12     //必须继承于partial
13     partial.call(this,animal);
14 }
15 animal.prototype = {
16     displayWeight: function () {
17         console.info(this.weight);
18     }
19 };
20 
21 par(animal, function () {
22     function p() {
23         this.name = "hello world";
24     }
25     p.prototype = {
26         displayName: function () {
27             console.info(this.name);
28         }
29     };
30     return p;
31 });
32 
33  var p = new animal();
34 */
35 
36 function par(cls, fn) {
37     if (!cls.parts) {
38         cls.parts = [];
39     }
40 
41     //append prototype
42     fn = fn();
43     var i;
44     for (i in fn.prototype) {
45         if (typeof (fn.prototype[i]) === "function") {
46             if (cls.prototype[i] != null && console) {
47                 console.warn("prototype(" + i + "):已经存在");
48             }
49             else {
50                 cls.prototype[i] = fn.prototype[i];
51             }
52         }
53     }
54 
55     //append property
56     cls.parts.push(fn);
57 }
58 
59 function partial(cls) {
60     var i;
61     for (i = 0; i < cls.parts.length; i++) {
62         cls.parts[i].call(this);
63     }
64 
65     //optimize
66     var reg = /^__[0-9a-zA-Z]+$/;
67     var j;
68     for(j in cls.prototype) {
69         if (reg.test(j)) {
70             delete cls.prototype[j];
71         }
72     }
73 }
posted @ 2012-11-10 10:24  mytree  阅读(245)  评论(0编辑  收藏  举报