js: accessing scope of parent class

前端 未结 7 580
生来不讨喜
生来不讨喜 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:04

    Use an Arrow Function

    An arrow function does not have it's own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope.

    Normal function syntax

    function(param1, param2) {}

    Arrow function syntax

    (param1, param2) => {}

    Usage

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

    Using an Arrow function within a ECMAScript 2015 Class

    class simpleClass {
    
        constructor() {
            this.status = 'pending';
            this.target = jqueryObject;
        }
    
        updateStatus() {
            this.target.faceOut('fast', () => {
                this.status = "complete";
            });
        }
    }
    
    const s = new simpleClass();
    s.updateStatus();
    

    Described code works only in modern browsers.

提交回复
热议问题