tags:

views:

81

answers:

1

I have some example jscript 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?
+1  A: 

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.

Moishe