JDo
JDo

Reputation: 123

Calling a public function without creating a new object JS

I'm playing with JS "oop" (or should i say "pop" - prototype oriented programming?) and tried to do something like static method and functions. I can call function from prototype object but that isn't exactly static function, is it?

I have that code:

function a(val){
   this.val = val;
   console.log(this);
   this.foo = function(){
     console.log('hi');
   }
 }

And i want to call the foo function without creating a new object. Is something like this is possible? How can i do it?

Upvotes: 0

Views: 2021

Answers (2)

Dan Crews
Dan Crews

Reputation: 3607

If you're trying to mimic static functions, you'll need to add the methods after you create the "class":

function A(val) {
    this.val = val;
}

A.foo = function() {
    console.log('hi');
}

Then you can call A.foo(); without having to use the prototype. It's a lot like the way Object.keys works. This makes it a property of the function, rather than a property of the instance, like static functions.

Upvotes: 2

Ben Aston
Ben Aston

Reputation: 55739

As written, you cannot call foo without instantiating a.

The best you can do is hide the instantiation of the object like so:

var a = {
  foo: function() { 
    console.log('hi');
  }
};

As regard to simulating static functions, this is the closest you can come:

function A(val) {
  this.val = val;
  console.log(this);
}

A.prototype.foo = function() { console.log('hi'); };

You do not need to instantiate A to call foo at this point.

A.prototype.foo(); // 'hi'

Upvotes: 0

Related Questions