Search code examples
javascriptscopeparentjavascript-objects

JavaScript access parent scope


I'm having a hard time figuring out how to access the parent's class scope. My code is as follows

var Class = function(){
    this.smth = 3;
}

Class.prototype.setters = {};
Class.prototype.setters.smth = function(smth){
    this.smth = smth;
}

However this of course does not work, it affects smth to Class.setters. I tried using .bind(Class.prototype); to no avail. Does anyone have a solution? I've got plenty of sub-methods.


Solution

  • When you call someInstance.setters.smth(...) the this of the function call is the settings object, and there's no way for that smth function to know how the settings object is being accessed, only that it is being provided as a this.

    You could keep your desired syntax but at significant memory cost by creating a unique setters object for each instance, inside your constructor:

    var Class = function(){
        var thisClassInstance = this;
        this.smth = 3;
        this.setters = {};
        this.setters.smth = function(smth){
            thisClassInstance.smth = smth;
        }
    }
    

    This is suboptimal because you lose the benefits of prototype inheritance; each instance has a suite of unique functions in the setters object and nothing is shared.

    A leaner way would be to have each instance has its own setters object that knows the identity of its parent instance, but that setters object inherits all its methods from a prototype setter object:

    // all `setters` object inherit their methods from this object
    var settersPrototype = {};
    
    // methods on the `setters` set values on `this.parent`
    settersPrototype.smth = function(smth){
        this.parent.smth = smth;
    }
    
    var Class = function(){
        this.smth = 3;
    
        // this instance has a `setters` object that inherits all its methods
        this.setters = Object.create(settersPrototype);
        this.setters.parent = this;
    }
    

    This way, you have a mild memory cost of a unique { parent: ... } object per instance, but there is a single prototype version each setter function, present on the one-and-only settersPrototype object.