bobince wrote a nice post how to write "classes" in JavaScript: How to "properly" create a custom object in JavaScript?
As the article says, there are two ways to write classes in JavaScript: - the closure way - the prototype way
But it's also possible to write classes using the module pattern, isn't it? I'm confused as there is so much information about JavaScript and some of them are contradictory.
Example class with module pattern (?):
var MyClass = function () {
// Private variables
var firstName;
var secondName;
// Public functions
return {
getFullName: function () {
return (this.firstName + " " + this.secondName);
},
setFirstName: function (value) {
this.firstName = value;
},
setSecondName: function (value) {
this.secondName = value;
},
getFirstName: function (value) {
return this.firstName;
},
getSecondName: function (value) {
return this.secondName;
}
}
};
describe("test module", function () {
it("Test instance", function () {
var myInstance = new MyClass("Michael", "Jackson");
expect(myInstance).not.toBeNull();
});
it("setter and getter", function () {
var myInstance = new MyClass("Michael", "Jackson");
myInstance.setFirstName("Michael");
myInstance.setSecondName("Jackson");
expect(myInstance.getFirstName()).toBe("Michael");
expect(myInstance.getSecondName()).toBe("Jackson");
expect(myInstance.getFullName()).toBe("Michael Jackson");
});
it("Test instances", function () {
var myInstance1 = new MyClass();
myInstance1.setFirstName("Michael");
myInstance1.setSecondName("Jackson");
var myInstance2 = new MyClass();
myInstance2.setFirstName("Paris");
myInstance2.setSecondName("Hilton");
expect(myInstance1.getFullName()).toBe("Michael Jackson");
expect(myInstance2.getFullName()).toBe("Paris Hilton");
expect(myInstance1 != myInstance2).toBe(true);
});
});