Skip to content Skip to sidebar Skip to footer

Acess To This From Subobject In JavaScript

How do I get access to the properties or method of the main object, from sub-obiect level two (sub3). If possible I would like to avoid solutions chaining return this. Obj = functi

Solution 1:

With your current syntax, you can't. Because for sub2 and sub3, the this variable is Obj.prototype.subobject.

You have multiple choice:

  • The obvious one: don't use a suboject.
  • Create subobject, sub2 and sub3 in the constructor

    Obj = function() {
        var self = this;
    
        this.subobject = {
            sub1: function() { console.log(self); }
        }
    }
    
  • Use bind at each call:

    o.subobject.sub2.bind(o)();
    

Post a Comment for "Acess To This From Subobject In JavaScript"