Both prototypes and closures can be used within a revealing module. The examples above can both be used inside of a revealing module. For example, if I want to wrap the Customer and VipCustomer classes within a common namespace, I can use the following:new MyNamespace.MyModule.MyClass(arguments)
).
function Customer(name) {
this.name = name;
}
Customer.prototype = {
constructor: Customer,
greet: function () {
return this.name + ' says hi!';
}
};
REVEALING MODULE PATTERN with Prototype
function Customer(name) {
this.name = name;
}
Customer.prototype = {
constructor: Customer,
greet: function () {
return this.name + ' says hi!';
}
};
function VipCustomer(name, discountPercentage) {
Customer.call(this, name);
this.discountPercentage = discountPercentage;
}
VipCustomer.prototype = new Customer();
VipCustomer.prototype.constructor = VipCustomer;
return {
Customer: Customer,
VipCustomer: VipCustomer
};
}());
var steve = new Fenton.Customer('Steve');
var todd = new Fenton.VipCustomer('Todd', 10);
Constructor-functions and prototypes are one of the reasonable ways to implement classes and instances. You need to choose a particular scheme or helper method to implement classes in terms of prototypes. ( Read ...)
The module pattern is typically used for namespacing, where you'll have a single instance acting as a store to group related functions and objects. This is a different use case from what prototyping is good for.
They're not really competing with each other; you can quite happily use both together (eg put a constructor-function inside a module and say
Prototype
Module
var customer = (function (name) {
var greet = function () { return “hello " + name; };
return {
greet: greet
}
})(“John");
var Fenton = (function () {
Finally I do not agree with people suggesting to never use ‘new’ keyword. Language designers provided it for a reason, avoid valid language constructs for short term goals lead to unmaintainable and hard to read code. Yet I would have some reservations about capitalizing and using new to initialize modules, I would prefer jQuery.something than (new jQuery).something
Resources :