Dynamic Prototype Pattern
Description
The dynamic prototype pattern encapsulates all of the information within the constructor by initializing the prototype if needed.
Example
function Person(name, age, job){/*from w w w . j ava2s . co m*/
//properties
this.name = name;
this.age = age;
this.job = job;
//methods
if (typeof this.sayName != "function"){
Person.prototype.sayName = function(){
console.log(this.name);
};
Person.prototype.printAge = function(){
console.log(this.age);
};
}
}
var friend = new Person("XML", 29, "mark up");
friend.sayName();
friend.printAge();
The constructor adds the sayName() method if it doesn't already exist.
This block of code is executed only the first time the constructor is called.
The if
statement may check for any property or method that will be present once initialized,
there's no need for multiple if statements to check each property or method.
The code above generates the following result.