0

I want to say:

 var b = new a.B();

where a is an object. I want the method B to be able to refer to the calling object a and to the newly created object b.

Normally, first reference is achieved via method context and second - via constructor context. Both contexts bind referenced objects to this keyword.

But how do I refer to both of them during a single call to B?

USE CASE:

Suppose, that I've written a library that allows user to easily insert my widget inside his web-page. Upon load my library exports a single name to the global namespace: Toolbar, which is a constructor that creates my widget within user's web-page element, called parent_dom_element:

var toolbar1 = new Toolbar(parent_dom_element);

Now, within my widget, corresponding to toolbar1 object, user can create sub-widgets like this:

var comment = new toolbar1.Comment();

I want the constructor function Comment to be able to refer to the toolbar1 object and to act as a constructor at the same time like this:

Toolbar.prototype.Comment = function (toolbar, ){
    this.attr1 = toolbar.attr1;
};

How to achieve this?

Boris Burkov
  • 13,420
  • 17
  • 74
  • 109
  • You can do `new a().B()`, but `b` variable will be set to whatever `.B` returns. Unless you return the object itself on `.B`, you will lose reference to the newly constructed `a`. Is this what you want? – Ortiga Aug 25 '14 at 10:34
  • @Bob can you elaborate your question. Please make me clear what you expect ? – pramod Aug 25 '14 at 10:34
  • Possible duplicate of [Organize prototype javascript while perserving object reference and inheritance](http://stackoverflow.com/q/15884096/1048572), see also [constructor inside constructor - bad practice?](http://stackoverflow.com/q/20784304/1048572) – Bergi Aug 25 '14 at 11:08
  • @pramod I've added an example for my question. I hope, it is concise and clear enough. – Boris Burkov Aug 25 '14 at 11:31

1 Answers1

1

You have to define a var inside Toolbar context pointing to 'this' and define the Comment constructor inside the Toolbar constructor. This way, the Comment contructor will get access to the 'toolbar' variable.

var Toolbar = function () {
    var toolbar = this;  // toolbar = Toolbar instance
    this.attr1 = "";     // this = Toolbar instance

    this.Comment = function () {
        this.attr1 = toolbar.attr1;  // this = Comment instance;
    };
};

var toolbar1 = new Toolbar();
var comment = new toolbar1.Comment();
Callebe
  • 1,087
  • 7
  • 18
  • If you're going to use this pattern, have a look at [constructor inside constructor - bad practice?](http://stackoverflow.com/q/20784304/1048572) – Bergi Aug 25 '14 at 15:26