2009-12-17 2 views
1

내가 생성자에 대한 Resig 씨의 makeClass() 방식 사용이 코드에서자바 스크립트 : 중첩 된 (내부) 유형의 기본 디자인은 무엇입니까?

// 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"); 

내가 (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

노트, 이것은이 완벽하게 작동, – Tyson

+0

감사합니다 단순한 1 분 예입니다. – Cheeso

관련 문제