2011-10-02 6 views
1

getters 및 setters 기능을 찾고 있지만 __defineGetter____defineSetter__에 아직 의존 할 수 없습니다. 그렇다면 함수 호출간에 함수 변수의 값을 어떻게 유지합니까? JavaScript 함수의 변수 상태 (값)를 호출간에 유지하는 방법은 무엇입니까?

나는 명백한 시도했지만 myVar에 항상 함수의 시작 부분에 정의되지 않는다 : 난 항상 단지 기능 이상 다른 FNS._itemCache = []을 넣을 수

FNS.itemCache = function(val) { 
    var myvar; 
    if(!$.isArray(myvar) 
     myvar = []; 
    if(val === undefined) 
     return myvar; 
    .. // Other stuff that copies the array elements from one to another without 
     // recreating the array itself. 
}; 

하지만, 거기는의 값을 캡슐화하는 방법입니다 함수 호출 사이?

당신은 현재 함수에 대한 참조로서 arguments.callee을 이용하여 함수의 값을 저장할 수
+1

닫는 괄호가 누락되어 있습니까 – mowwwalker

+0

비공개로해야합니까? – David

답변

3

개인 변수를 설정하는 또 다른 방법은 익명 함수에 함수 정의를 포장하는 것입니다 객체의 private 멤버를 만들기위한 표준 패턴 :

(function(){ 
    var myvar; 
    FNS.itemCache = function(val) { 
     if(!$.isArray(myvar)) 
      myvar = []; 
     if(typeof val == "undefined") 
      return myvar; 
     .. // Other stuff that copies the array elements from one to another without 
      // recreating the array itself. 
    }; 
})(); 

이렇게하면, myvarFNS.itemCache의 범위로 정의됩니다. 익명의 함수 래퍼로 인해 변수를 다른 곳에서 수정할 수 없습니다.

4

: 함수는 시제품에 저장되고, 따라서 더 이상이 사용되는 경우

FNS.itemCache = function(val) { 
    if(!$.isArray(arguments.callee._val) 
     arguments.callee._val = []; 
    if(val === undefined) 
     return arguments.callee._val; 
    .. // Other stuff that copies the array elements from one to another without 
     // recreating the array itself. 
}; 

그러나이 침입 할 목적. 이 경우 멤버 변수 (예 : this._val)를 사용해야합니다.

4

이 정적 변수를 생성하고

FNS.itemCache = (function() { 
    var myvar; 
    if(!$.isArray(myvar) 
     myvar = []; 
    return function(val) { 
     if(val === undefined) 
      return myvar; 
     .. // Other stuff that copies the array elements from one to another without 
     // recreating the array itself. 
    } 
})(); 
관련 문제