1

I was reading about the best methods to create objects in javascript and found an interesting solution here.

var Foo = function()
{

    var privateStaticMethod = function() {};
    var privateStaticVariable = "foo";

    var constructor = function Foo(foo, bar)
    {
        var privateMethod = function() {};
        this.publicMethod = function() {};
    };

    constructor.publicStaticMethod = function() {};

    return constructor;
}();

I have been playing with this structure but I was wondering how can I do a few things.

  • How can I access privateStaticVariable or privateStaticMethod from within constructor.publicStaticMethod?

  • If I create a second public method like constructor.secondPublicStaticMethod = function(){};, how can I access it from within constructor.publicStaticMethod?

  • If I was to instantiate this object, how could I access all static properties and methods from within constructor?

Community
  • 1
  • 1
CIRCLE
  • 4,501
  • 5
  • 37
  • 56

1 Answers1

3

How can I access privateStaticVariable or privateStaticMethod from within constructor.publicStaticMethod

You can access them simply by using their names because they are enclosed variables within constructor.publicStaticMethod because of the closure property.

If I create a second public method like constructor.secondPublicStaticMethod = function(){};, how can I access it from within constructor.publicStaticMethod

Since secondPublicStaticMethod is a function defined on the constructor object, you can simply invoke it like constructor.secondPublicStaticMethod

If I was to instantiate this object, how could I access all static properties and methods from within constructor

This is similar to the above mentioned. You can access privateStaticVariable and privateStaticMethod simply by writing privateStaticVariable and privateStaticMethod respectively. And the functions defined on constructor can be accessed with constructor.publicStaticMethod

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497