那麼有一些方法來定義類。
// serves as a constructor
function MyClass(name, id) {
// init members.
// this.members are public members
this.Name = name;
this.Id = id;
// this is a private member available only in constructor
var something = 0;
this.DoSomething = function() {
// your method
// here you also can use something here as you have access.
}
}
MyClass.prototype = {
// This also another way to define your methods
"SomeMethod": function (input) {
// Do something
// you don't have access to private members in constructor.
}
}
而且,如果你想要更多的OOP特性
function AnotherClass (input) {
// private field
var someNumber = 0;
// get accessor
this.getSomeNumber = function() {
return someNumber;
}
this.setSomeNumber = function(value) {
if (typeof value != "number" || value != value)
throw new Error("Your value must be a number");
someNumber = value;
}
}
如果你想要一些靜態方法,那麼這裏有他們
var MyThirdClass = (function() {
var instanceCount = 0;
function _Constructor() {
this.Name = "";
instanceCount++;
}
_Constructor.getInstanceCount = function() {
return instanceCount;
}
return _Constructor;
})();
最後,你可以按照如下
使用它們
var myClass = new MyClass("Foo", 1);
myClass.Name = "Bar";
myClass.DoSomething();
var thirdClass = new MyThirdClass();
var thirdClassAnotherInstance = new MyThirdClass();
alert(MyThirdClass.getInstanceCount());