2009-12-17 30 views
1

我使用的構造Resig的makeClass()的方法:Javascript:嵌套(內部)類型的首選設計是什麼?

// makeClass - By John Resig (MIT Licensed) 
// Allows either new User() or User() to be employed for construction. 
function makeClass(){ 
    return function(args){ 
    if (this instanceof arguments.callee) { 
     if (typeof this.init == "function") 
      this.init.apply(this, (args && args.callee) ? args : arguments); 
    } else 
     return new arguments.callee(arguments); 
    }; 
} 

// usage: 
// ------ 
// class implementer: 
// var MyType = makeClass(); 
// MyType.prototype.init = function(a,b,c) {/* ... */}; 
// ------ 
// class user: 
// var instance = new MyType("cats", 17, "September"); 
//  -or- 
// var instance = MyType("cats", 17, "September"); 
// 



var MyType = makeClass(); 

MyType.prototype.init = function(a,b,c) { 
    say("MyType init: hello"); 
}; 

MyType.prototype.Method1 = function() { 
    say("MyType.Method1: hello"); 
}; 

MyType.prototype.Subtype1 = makeClass(); 

MyType.prototype.Subtype1.prototype.init = function(name) { 
    say("MyType.Subtype1.init: (" + name + ")"); 
} 

在該代碼中,的MyType()是一個頂級類型,MyType.Subtype1是嵌套類型。

要使用它,我可以這樣做:

var x = new MyType(); 
x.Method1(); 
var y = new x.Subtype1("y"); 

我能到父類型的實例的引用,在init()爲Subtype1內()? 如何?

回答

2

不,除非你寫了一個明確跟蹤這個「外層」類的類實現,否則Javascript將無法把這個給你。

例如:

function Class(def) { 
    var rv = function(args) { 
     for(var key in def) { 
      if(typeof def[key] == "function" && typeof def[key].__isClassDefinition == "boolean") 
       def[key].prototype.outer = this; 
      this[key] = def[key]; 
     } 

     if(typeof this.init == "function") 
      this.init.apply(this, (args && args.callee) ? args : arguments); 
    }; 

    rv.prototype.outer = null; 
    rv.__isClassDefinition = true; 
    return rv; 
} 

var MyType = new Class({ 
    init: function(a) { 
     say("MyType init: " + a); 
     say(this.outer); 
    }, 

    Method1: function() { 
     say("MyType.Method1"); 
    }, 

    Subtype1: new Class({ 
     init: function(b) { 
      say("Subtype1: " + b); 
     }, 

     Method1: function() { 
      say("Subtype1.Method1"); 
      this.outer.Method1(); 
     } 
    }) 
}); 

var m = new MyType("test"); 
m.Method1(); 

var sub = new m.Subtype1("cheese"); 
sub.Method1(); 
+0

注意,有一百萬個不同的方式來寫一個類實現,這只是一個簡單的1分鐘例如 – Tyson 2009-12-17 22:59:10

+0

謝謝你,這完美地工作。 – Cheeso 2009-12-18 03:50:06