user34537
user34537

Reputation:

Static functions in JavaScript?

I have some example javascript code and I would like the function to be static.

package pkg { class b { public function increment(x) { return x+1; } } }
//in C#
methInfo.Invoke(null, params); //error bc of null. I dont know how to create class b ATM
//i dont need b so i would like to call the func like this. How do i make increment static?

Upvotes: 0

Views: 257

Answers (1)

Moishe Lettvin
Moishe Lettvin

Reputation: 8471

The standard in code that I use and write is:

MyAwesomeClass = function() {
  this.memberVariable_ = "some-value";
};

MyAwesomeClass.staticFunction = function(x) {
  return x + 1;
};

MyAwesomeClass.prototype.instanceFunction = function(y) {
  this.memberVariable_ += y;
};

So to use this class you'd do something like:

// Call an instance method
myClassInstance = new MyAwesomeClass();
myClassInstance.instanceFunction(foo);

// Call a static method
var baz = MyAwesomeClass.staticFunction(bar);

The thing to remember about Javascript is that the class itself is an object, so you're setting properties of that object to functions. The 'prototype' property is the special case for instance methods.

Upvotes: 1

Related Questions