vilbur
vilbur

Reputation: 1

Self referencing nested objects

Dear JavaScript masters.

I understand to dozens of articles about scopes, objects, this keyword etc.
But these shows only basic examples.
Most of code I saw is long and messy JavaScripts.

I would like to achieve behavior, where 'this' in each object is referencing to object itself.
This test snippet has the required behavior.

QUESTION:
Is there a better way to achieve this ?
Is't it anti-pattern ?

var mainObject = {};
mainObject.childObject = {};

/* CHILD OBJECT
 */
(function() {

        function childObject(){
                this.property = 'childObject';
                this.childMethod = function(){
                        console.log( 'child obj method' );
                };
        }
        return childObject;

})().apply(mainObject.childObject);


/* MAIN OBJECT
 */
(function() {

        function mainObject(){
                this.property = 'mainObject';
                console.log( 'main obj method' );
                this.childObject.childMethod();
        }
        return mainObject;

})().apply(mainObject);



console.log( mainObject );
console.log( mainObject.childObject );

Upvotes: 0

Views: 436

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51886

Not sure if it qualifies as an "anti-pattern" per se, but there are certainly a lot of unnecessary things going on. Here's a simplified example, maintaining the static functions you declared:

var mainObject = {};
mainObject.childObject = {};

function modifyChild() {
  this.property = 'childObject';
  this.childMethod = function() {
    console.log('child obj method');
  };
}

modifyChild.call(mainObject.childObject);

function modifyMain() {
  this.property = 'mainObject';
  console.log('main obj method');
  this.childObject.childMethod();
}

modifyMain.call(mainObject);

console.log(mainObject);
console.log(mainObject.childObject);

In general, if you want a static function you can call directly, without chaining .call() or .apply(), and pass in a this context, you can .call.bind() it to itself:

var someFunction = (function () {
  function someFunction () {
    console.log(this);
  }
  
  return someFunction.call.bind(someFunction);
})()

someFunction({ foo: 'bar' });

Upvotes: 1

Related Questions