2

After some research on how to write modular/namespace in javascript, I saw that the following might be a good idea on how to encapsulate a function/object:

var MODULE = (function (parent) {
    var OB = parent;
    var TH = this;

    parent.num = 10;

    // method 1 - works ok, because we use normal function, "this" works as expected, returns 11
    parent.oneMore = function () { 
        return this.num + 1;
    };

    // method 2 - works ok, returns 12
    parent.twoMore = () => { return parent.num + 2;};

    // method 3 - works ok, returns 13
    parent.threeMore = () => OB.num + 3;

    // method 4 - does not work, returns NaN
    parent.fourMore = () => TH.num + 4;        

    // adding a property/method - which way would be better?
    parent.n1 = 100;        
    OB.n2     = 200;        
    this.n3   = 300; // non-sense       
    TH.n4     = 400; // also non-sense


    return parent;
}(MODULE || {}));


(function (m) {
    console.log(m.oneMore());
    console.log(m.twoMore());
    console.log(m.threeMore());
    console.log(m.fourMore());

    console.log(m.n1);
    console.log(m.n2);
    console.log(m.n3);
    console.log(m.n4);
})(MODULE);

Now, check the function twoMore(). When using array functions, we know that we can't pass use this directly.

So, instead, I decided to use OB, where OB = parent.

My question: is there any difference between using directly parent or OB? What exactly does parent represent?

Also, how to declare properties and methods? Using parent.prop = 1;, or OB.prop = 1; or anyother way?

Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
jack
  • 1,391
  • 6
  • 21

0 Answers0