2013-07-25 2 views
3

나는 "엄격한 사용"을 적용하고 SO post에서 가져온 John Resig의 간단한 OOP Class을 사용하고 있습니다. 모든 예에서
나는과 같이 Class.extend의 사용을 참조하십시오간략한 JavaScript OOP 클래스

var MyObj = Class.extend({ 
    init:function(){}, 
    prop: "Property" 
}); 

하지만 그런 방법으로 그것을 사용하는 나를 위해 큰 단점을 발견 - 나는 "개인"변수를 가질 수 없습니다, 그래서 매장 기준으로 할 수 없습니다 thisvar $this = this;입니다. 내 경우에 대한 해결책을 발견, 지금은 다음과 같은 방법으로 Class.extend를 사용 : 내 경우에는 작동

var MyObj = Class.extend(new function(){ 
    var $this = this; 
    this.init = function(){}; 
    this.prop = "Property"; 
}); 

다,하지만 난 알고 싶은 경우 장기적으로 나에게 문제가 발생할 수 있습니다 몇 가지 ?
내 응용 프로그램이 브라우저에서 더 많은 메모리를 소비하게됩니까?
내 요구 사항을 구현하기 위해 어떤 대안을 사용할 수 있습니까?

: 나는 주로 이벤트와 콜백을 사용하기 때문에 나는 $이를 저장해야하는, 그래서 난 "원래"참조 할 this 개체의 모든 메서드와 속성에 액세스하기 쉬운.

편집는 :

(function() { 
    "use strict"; 
    window.QuickPlay = Class.extend(new function() { 
     var $this = this; 

     this.init = function (initData) { 
      $this.elementsToHide.push(initData.el); 
      $(function() { 
       playProcessStart(); 
       Sys.Application.add_load(function() { 
        $find("ctl00_ContentPlaceHolderMain_ctrlPlayPopup1").add_closed(function() { $this.setElementsVisibility(""); }); 
       }); 
       $this.setElementsVisibility("hidden"); 
      }); 
     }; 

     this.elementsToHide = []; 

     this.setElementsVisibility = function (visibility) { 
      $.each($this.elementsToHide, function (i) { 
       $("#" + this).css("visibility", visibility); 
      }); 
     }; 
    }); 
}()); 
+3

아뇨, 아니요. 나는 이것이 정말로 당신을 위해 일한다고 믿을 수 없습니다. 이 "클래스"를 이벤트 및 콜백과 함께 사용하는 방법을 알려주십시오. 아마도 실제 코드를 게시 할 것입니다 (적어도'this this '를 포함하는 메소드는 적어도). – Bergi

+0

@Bergi @Bergi 예제를 추가했습니다.이 코드는 이미 QA 무대를 통과했습니다. –

+0

모든 객체 내부에서 현재 객체를 인식하는'this'에 액세스 할 수 있어야합니다. – travis

답변

1
나는 "개인"변수를 가질 수 없습니다

물론

당신이 할 수있는 . (현재 불필요한) (function() { … }()); 래퍼 또는 생성자 (init 건).

new function() { 

Avoid that pattern!은 당신이 정말로 그것을 지금처럼 작동

(function() { 
    "use strict"; 
    // Here's the place where you could put a private, static variable 
    // for example `var elementsToHide = [];` 
    var $this = { 
     init: function (initData) { 
      $this.elementsToHide.push(initData.el); 
      $(function() { 
       playProcessStart(); 
       Sys.Application.add_load(function() { 
        $find("ctl00_ContentPlaceHolderMain_ctrlPlayPopup1").add_closed(function() { 
         $this.setElementsVisibility(""); 
        }); 
       }); 
       $this.setElementsVisibility("hidden"); 
      }); 
     }, 
     elementsToHide: [], 
     setElementsVisibility: function (visibility) { 
      $.each($this.elementsToHide, function (i) { 
       $("#" + this).css("visibility", visibility); 
      }); 
     } 
    }; 
    window.QuickPlay = Class.extend($this); 
}()); 

내가 나에게 문제를 일으킬 수있는 몇 가지가 있는지 알고 싶어 사용하도록 코드가 필요한 경우

예. 복수 인스턴스는 거의 모두 작동하지 않을 것입니다. 모두 동일한 elementsToHide 배열을 참조하기 때문입니다. 그리고 (클래스의 생성자와 정적 요소에서만) 인스턴스 메서드를 사용하지 않으므로 클래스 패턴이 매우 불필요한 것처럼 보입니다. 대신 a module을 사용하십시오.단일 인스턴스 (및 클래스)가 필요한 경우 코드는 다음과 같아야합니다.

"use strict"; 

window.QuickPlay = Class.extend({ 
    init: function (initData) { 
     var $this = this; 
     this.elementsToHide = []; 
     $(function() { 
      playProcessStart(); 
      $this.elementsToHide.push(document.getElementById(initData.el)); 
      Sys.Application.add_load(function() { 
       $find("ctl00_ContentPlaceHolderMain_ctrlPlayPopup1").add_closed(function() { 
        $this.setElementsVisibility(""); 
       }); 
      }); 
      $this.setElementsVisibility("hidden"); 
     }); 
    }, 
    setElementsVisibility: function (visibility) { 
     $(this.elementsToHide).css("visibility", visibility); 
    } 
}); 
+0

클래스를 사용하는 방식으로 "거대한"문제를 지적 해 주셔서 감사합니다 ... 내 응용 프로그램에서 "singletons"및 클래스를 사용해야하므로 사용/생성해야합니다. 각각의 경우에 대해 두 가지 다른 패턴. 현재 프로젝트에서 JS OOP로 시작 했으므로 아직 변경하기에는 너무 늦지 않았습니다 :) –

+0

생성에 대한 데이터로 초기화해야하는 "모듈"을 만드는 방법을 좋은 패턴으로 가르쳐 주시겠습니까? –

+0

나는 싱글 톤 모듈을 "창조 (creation)"없이 매우 정적이라고 생각할 것이다. 나는 생각할 수있다. a) 데이터는 모듈 코드로 코딩된다. b) 모듈은 글로벌 "데이터 저장소"에서 데이터 자체를 가져온다. c) 글로벌 컨트롤러는 다음과 같이 데이터를 가진'init' 메소드를 호출하여 모듈을 시작한다. 인수. 코드 구조 패턴을 위해 링크 한 Osmani의 기사를 참조하십시오. – Bergi

2

당신은 모듈 패턴을 사용하는 모든 OOP를 유지할 수 있습니다 : 요청,이 내 코드의 예입니다. 이러한 종류의 패턴은 코드의 보안과 조직 성을 향상시킵니다. 상속 및 모듈 패턴 작업 방법 JsFiddle

  • 에서

    //these are namespaces in javascript 
    window.project = window.project || {}; //this kind declarations prevents recreate the object 
    project.group = project.group || {}; 
    
    //in the line below we can use $ instead jQuery, and use window and document instead ask for the browser every time. 
    (function (window, document, $) { 
        "use strict"; 
    
        project.group.NameOfYourModule = function() { 
         var privateAttribute = true, 
          students = 32, //It's is a best practice declare everything in an unique var. 
    
          privateMethod = function() { 
           alert('Now I know OOP using jQuery'); 
          }; 
    
         return { 
          init: function() { 
           //this is a public method and we can initiate some private method; 
           privateMethod(); 
    
           //we call a public method using this 
           this.publicMethod(); 
          }, 
          publicMethod: function() { 
           //this is a public method 
          } 
         }; 
        }; 
    
        $(function() { 
         var myclass = new project.group.NameOfYourModule(); //instantiate you class 
         myclass.init(); //initiate some public method 
        }); 
    }(window, document, jQuery)); 
    
    • 작업을 예를 here
  • +0

    상속은 어떻습니까? 패턴에서 어떻게 상속받는 MySecondModule을 만들 수 있습니까? –

    +0

    내가 상속 작용하는 방법을 설명하는 참조를 추가했습니다. 도와 줘서 기쁩니다 :) –

    +0

    고마워, 나는 링크를 보았습니다 ... 그것이 효과가있을 것이라고 확신하지만, 다른 팀 멤버들에게는 너무 복잡합니다. :(사용하기 쉬운 것을 시도하고 있습니다.) –