0

How can I declare non-global static methods in js?

foo.bar = function() {
  function testing{
    console.log("statckoverlow rocks!");
  }
  function testing2{
    console.log("testing2 funtction");
  }
}

How can I call the testing functions? I am a newbie in JS.

Thanks for help.

4 Answers 4

3

You probably want an object.

foo.bar = {
  testing: function() {
    console.log("statckoverlow rocks!");
  },
  testing2: function() {
    console.log("testing2 funtction");
  }
};

Then, call foo.bar.testing(), for example.

Sign up to request clarification or add additional context in comments.

Comments

1

You could do like this:

foo.bar = (function() {
  var testing = function () {
    console.log("statckoverlow rocks!");
  };
  var testing2 = function () {
    console.log("testing2 funtction");
  };
  return {
    testing: testing,
    testing2: testing2
  };
}());

// call them
foo.bar.testing();
foo.bar.testing2();

2 Comments

why do we need for.bar = (function() {.....}()); it seems make things complicated
@Kit Ho It's a self executing function that creates a singleton. If you're using "classes" or prototypes in JavaScript, check my answer I believe that's what you mean by static method.
1

Did you mean:

var foo = {
    bar: {
        testing: function()
        {
            console.log("statckoverlow rocks!");
        },
        testing2: function()
        {
            console.log("testing2 funtction");
        }
    }
};


foo.bar.testing();
foo.bar.testing2();

Comments

0
// Constructor
function Foo() {
  var myvar = 'hey'; // private
  this.property = myvar;
  this.method = function() { ... };
}
Foo.prototype = {
  staticMethod: function() {
    console.log( this.property );
  }
}
var foo = new Foo();
foo.staticMethod(); //=> hey

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.