在javascript中实现分部类定义
<div id="cnblogs_post_body"> 在定义类时,如果这个类足够的大,为了方便管理,会把类定义在不同的文件,但是在javascript中没有这样的功能,为了简化工作做了一个可以实现分部类定义的功能.其实现原理主要是通过修改原型链和call.
代码如下:
<div class="cnblogs_code"> 1 /* 2 实现分部类定义 3 4 定义时,如果prototype(及方法)名称以(__)开头的话,将视为临时方法,及只在初始化进行执行,后续不在需要,在执行完成后会删除此方法, 5 目的是为了减小instance,因此在定义私有prototype(方法)时,请用(_)开头 6 7 8 9 Example:10 function animal() {11 this.weight = 100;12 //必须继承于partial13 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 prototype42 fn = fn();43 var i;44 for (i in fn.prototype) {45 if (typeof (fn.prototype) === "function") {46 if (cls.prototype != null && console) {47 console.warn("prototype(" + i + "):已经存在");48 }49 else {50 cls.prototype = fn.prototype;51 }52 }53 }54 55 //append property56 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.call(this);63 }64 65 //optimize66 var reg = /^__+$/;67 var j;68 for(j in cls.prototype) {69 if (reg.test(j)) {70 delete cls.prototype;71 }72 }73 }
页:
[1]