1

I have a class foo, can I access its public method bar with out initializing fooObj

var foo = function(){
   this.bar = function(){
       console.log("I am bar");
   }
}

I know I can access bar like

var fooObj = new foo();
fooObj.bar();

In other object oriented language like javeif I declare bar static I can access it with class name like foo.bar

1
  • 1
    Do not think in terms of "classes". Javascript doesn't have those. It's all just objects with properties. Commented May 12, 2015 at 10:22

1 Answer 1

4

There is no static concept like Java but you can do something like

var foo = function(){
   // Constructor specific code
}

foo.bar = function(){
    console.log("I am bar");
}

This is how singleton will be defined in JavaScript

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

3 Comments

If you add it to prototype, it should work when you instantiate an object and call the method present in it.
@ Vigneswaran Marimuthu I didn't get what I wanted as, deceze said Do not think in terms of "classes". Javascript doesn't have those. It's all just objects with properties.
@ozil What he meant is there is no concept of classes like in Java. If you see JavaScript you can see concepts like functions, objects and properties. Constructors are created using functions not classes in JavaScript. Though ES6 have classes concept but it's relatively new - javascriptplayground.com/blog/2014/07/…

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.