开发者

Static functions in JavaScript?

开发者 https://www.devze.com 2022-12-11 01:28 出处:网络
I have some example javascript code and I would like the function to be static. pac开发者_如何学编程kage pkg { class b { public function increment(x) { return x+1; } } }

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

pac开发者_如何学编程kage 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号