- i_love_sc
- 等级:
- 性别:
- 文章: 223
- 积分: 168
- 来自: 上海
|
特性:
用了原型链继承作为基础(Ext), 如果有覆写的方法,就把原方法存入新方法的base属性(mootools)。
使用了closure的设计模式,隐藏了内部使用的extend。
相对base2来说简单了许多。
js 代码
-
-
-
-
-
-
- var Class = (function() {
- var get_proto = function(base) {
- var F = function(){};
- switch (typeof base) {
- case "undefined":
- return {};
- case "object":
- F.prototype = base;
- F.prototype.constructor = F;
- return new F();
- case "function":
- F.prototype = base.prototype;
- F.prototype.constructor = F;
- var f = new F();
- f.constructor = base;
- return f;
- }
- };
-
- var extend = function(cur, pre) {
- for (var p in cur) {
- var prep = pre[p];
- var curp = cur[p];
- if (typeof curp == "function" && typeof prep == "function") {
- curp.base = prep;
- }
- pre[p] = curp;
- }
- return pre;
- };
-
- var mix = function() {
- for (var i = 0, a = arguments, len = a.length; i < len; i++) {
- var ai = a[i];
- if (typeof ai == "function") {
- ai = get_proto(ai);
- }
-
- for (var p in ai) {
- if (p != "constructor") {
- this.prototype[p] = ai[p];
- }
- }
- }
- };
-
- var get_constructor = function() {
- var native_constructor = Object.prototype.constructor;
- for (var i = 0, a = arguments, len = a.length; i < len; i++) {
- var ctor = a[i].constructor;
- if (ctor != native_constructor) {
- return ctor;
- }
- }
- return function(){};
- };
-
- return {
- create: function(props, base) {
- var base_props = get_proto(base);
- var F = get_constructor(props, base_props);
- F.prototype = extend(props, base_props);
- F.prototype.constructor = F;
- F.mix = mix;
- return F;
- }
- }
- })();
test
js 代码
-
-
- var A = Class.create({
- constructor: function(name) {
- this.name = name;
- },
-
- getName: function() {
- return this.name
- }
- });
-
- var B = Class.create({
- constructor: function(name) {
- arguments.callee.base.call(this, "B:" + name);
- }
- }, A);
-
-
- var a = new A("I am a");
- var b = new B("I am b");
-
-
- A.prototype.num1 = 1;
- B.prototype.num2 = 2;
-
- var C = Class.create({
- m1: "m1"
- });
-
- A.mix(
- {
- m2: "m2"
- },
- C
- );
-
- a.change_prop = function() {
-
- this.constructor.prototype.tem = "tem";
- };
-
- a.change_prop();
-
-
-
-
-
-
-
-
-
-
-
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
返回顶楼 |
|
|