Program Tip

Node.js : 부모 클래스의 범위에 액세스

programtip 2020. 12. 3. 19:11
반응형

Node.js : 부모 클래스의 범위에 액세스


자바 스크립트의 일반 클래스 내에 jquery 클래스가 있습니다. jquery 클래스의 콜백 함수에서 부모 클래스 범위의 변수에 액세스 할 수 있습니까?

내가 의미하는 바의 간단한 예가 아래에 나와 있습니다.

var simpleClass = function () {    
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() {
        this.target.fadeOut("fast",function () {
           this.status = "complete"; //this needs to update the parent class 
        });
    };
};

이제 위의 예에서 콜백 함수는 jquery 객체의 범위에 액세스하려고합니다. 부모 클래스의 상태 변수에 액세스하는 방법이 있습니까?


"this"를 부모 함수의 변수로 설정 한 다음 내부 함수에서 사용합니다.

var simpleClass = function () {         
    this.status = "pending";     
    this.target = jqueryObject;     

    var parent = this;

    this.updateStatus = function() {         
            this.jqueryObject.fadeOut("fast",function () {            
                parent.status = "complete"; //this needs to update the parent class          
            });     
        }; 
    }; 

나는 아직 아무도 이것을 게시하지 않았기 때문에 어쨌든이 오래된 질문에 대한이 답변을 게시 할 것입니다.

bind함수 호출 에서 메서드를 사용하여 this속하는 범위를 정의 할 수 있습니다.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

일반적으로 메서드를 만들 때마다- this함수의 현재 범위에 속합니다. scope2의 변수는 scope1의 변수를 볼 수 없습니다.

예 :

function(){
    // scope 1
    this.baz = 'foo';

    function(){
        // scope 2
        this.baz // not defined
    };
};

bind방법 당신은에서 범위를 정의 할 수 있습니다 this함수 내부. 따라서 .bind(this)다음과 같이 호출 된 함수에 자신의 범위 this가 부모 함수의 범위를 참조 한다는 것을 알려줍니다 .

function(){
    // scope 1
    this.baz = 'foo';

    function(){
        // scope 1
        this.baz // foo
    }.bind(this);
};

따라서 귀하의 경우 이것은 bind방법을 사용하는 예입니다.

var simpleClass = function () {    
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() {
        this.target.fadeOut("fast",function () {
           this.status = "complete"; //this needs to update the parent class 
        }.bind(this));
    }.bind(this);
};

사용 화살표 기능

화살표 기능에는 자체 this. this둘러싸는 어휘 범위 값이 사용됩니다. 화살표 함수는 일반 변수 조회 규칙을 따릅니다. 따라서 this현재 범위에없는 것을 검색하는 동안 주변 범위 this에서 찾는 결과 가 나타 납니다 .

일반 함수 구문

function(param1, param2) {}

화살표 함수 구문

(param1, param2) => {}

용법

const simpleClass = function () {    
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() { 
        this.target.fadeOut("fast", () => { // notice the syntax here
           this.status = "complete"; // no change required here
        });
    };
};

ECMAScript 2015 클래스 내에서 Arrow 함수 사용

class simpleClass {

    constructor() {
        this.status = 'pending';
        this.target = jqueryObject;
    }

    updateStatus() {
        this.target.faceOut('fast', () => {
            this.status = "complete";
        });
    }
}

const s = new simpleClass();
s.updateStatus();

설명 된 코드는 최신 브라우저 에서만 작동 합니다 .


죄송합니다 m8. 다음과 같이 참조를 객체에 중첩해야합니다.

var simpleClass = function () {
    var _root = this;
    this.status = "pending";
    this.target = jqueryObject;
    this.updateStatus = function() {
        this.root = _root;
        _root.target.fadeOut("fast",function () {
           this.status = "complete"; //this needs to update the parent class 
        });
    };
};

주목 var _root


설정하여 "이" 변수에 쉽게 액세스 할 수 있습니다. 처럼:

$("#ImageFile").change(function (e) {
    var image, file;
    var Parent=this;
    if ((file = Parent.files[0])) {
        var sFileExtension = file.name.split('.')[file.name.split('.').length - 1];

        if (sFileExtension === "jpg" || sFileExtension === "jpeg" || sFileExtension === "bmp" || sFileExtension === "png" || sFileExtension === "gif") {
            var reader = new FileReader();

            reader.onload = function (e) {
               alert(Parent.files[0].name);
            };
            reader.readAsDataURL(Parent.files[0]);
        }
        else { alert('Wrong file selected. Only jpg, jpeg, bmp, png and gif files are allowed.'); }
    }
})

이 시도:

   var sc = (function(scc){

    scc = {};

    scc.target = jQueryObject;


    scc.stt = "stt init";

    scc.updateStatus = function(){
        var elem = this;

        this.target.click(function(){
            elem.stt= "stt change";
            console.log(elem.stt);
        })

    }

    return scc;


}(sc || {}));

대상 개체를 개인 변수로 정의 할 수도 있습니다.


클로저 변수를 사용하여 상태를 관리 할 수 ​​있습니다.

function simpleClass() {
   var _state = { status: "pending", target: jqueryObject; }

   this.updateStatus = function() {
      this.target.fadeOut("fast",function () {
         _state.status = "complete"; //this needs to update the parent class 
      });
   }
}

// Later...
var classInstance = new simpleClass();

참고URL : https://stackoverflow.com/questions/5106284/js-accessing-scope-of-parent-class

반응형