js: accessing scope of parent class

前端 未结 7 572
生来不讨喜
生来不讨喜 2021-01-31 13:45

I have a jquery class within a normal class in javascript. Is it possible to access variables in the scope of the parent class from a callback function in the jquery class?

7条回答
  •  后悔当初
    2021-01-31 14:00

    I will post this answer to this old question anyway as no one yet posted this before.

    You can use the bind method on your function calls to define the scope which this belongs to.

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

    Normaly everytime you create a method - this belongs to the current scope of the function. Variables from scope2 can't see variables from scope1.

    e.g.

    function(){
        // scope 1
        this.baz = 'foo';
    
        function(){
            // scope 2
            this.baz // not defined
        };
    };
    

    with the bind method you can define the scope from this inside the function. So using .bind(this) you're telling the called function that their own scope from this is referred to the scope of the parent function, like:

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

    so in your case, this would be an example using the bind method

    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);
    };
    

提交回复
热议问题