The ‘new’ keyword and the revealing module pattern
The following is the regular way of using a constructor. What it does it actually returns “this”, like having a secret return this; at the end. If functions(methods) are not added to the prototype they are created each time for each object.
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
};
var person1 = new Person(‘Foo’, 99, 'Javascript’);
var person2 = new Person('Bar’, 15, 'UX’);
alert(person1 instanceof Object);//true
alert(person1 instanceof Person);//true
alert(person1.sayName == person2.sayName);//false
This is the revealing module pattern. It overrites the return of “this” by returning our own custom object when we use new with it. By doing this we loose the link to the constructor. All properties and methods are created each time regardless of using new or not with it.
function Person(name, age, job){
var name = name;
var age = age;
var job = job;
var sayName = function(){
alert(this.name);
};
return{
name: name,
age: age,
job: job,
sayName: sayName
}
};
var person1 = new Person('Foo’, 99, 'Javascript’);
var person2 = Person('Bar’, 15, 'UX’);
alert(person1 instanceof Object);//true
alert(person1 instanceof Person);//false
alert(person1.sayName == person2.sayName);//false
To use constructors with the module pattern we can use the following pattern, a module that returns a constructor:
var Person = (function () {
// private properties and methods
var Constr, private, secret,
// public API
Constr = function (name) {
this.name = this.sayName(name);
};
// public API – prototype
Constr.prototype = {
constructor: Person,
sayName : function(str){
return str;
}
};
// return the constructor
return Constr;
}());
var person1 = new Person('Foo’);
var person2 = new Person('Bar’);
alert(person1 instanceof Object);//true
alert(person1 instanceof Person);//true
alert(person1.name== person2.name);//false
alert(person1.sayName == person2.sayName);//true
The methods are not created twice for each instance, and we can also keep a reference from the new object to the constructor.
1 Notes/ Hide
- jesusgollonet liked this
- ipopa posted this