Construction method
function coder()
{
this.name = 'Modern Magic';
this.job = 'Web Developer';
this.coding = function ()
{ alert('I'm writing code'); }
}
var coder = new coder();
alert(coder.name);
coder.coding();
Factory method
function createCoderFactory()
{
var obj = new Object();
obj.name = 'Modern Magic';
obj.job = 'Programmer';
obj.coding = function ()
{
alert('I'm writing code');
};
return obj;
}
var coder = createCoderFactory();
alert(coder.name);
coder.coding();
Both factory methods and constructor methods have the same disadvantage, that is, every time an instance is created, each function of the class will be instantiated.
Prototype chain
function coder(){}
coder.prototype.name = 'Modern Magic';
coder.prototype.job = 'Programmer';
coder.prototype.coding = function(){
alert('I am writing code ');
};
var coder = new coder();
alert(coder.name);
coder.coding();
The prototype chain has One disadvantage is that all its properties are shared. As long as one instance changes, the others will change accordingly. Such as:
var coder1 = new coder();
var coder2 = new coder();
alert(coder1.name); /*Show modern magic*/
coder2.name = 'nowamagic';
alert(coder1.name); /*Show nowamagic* /
alert(coder2.name); /*This also shows nowamagic*/
Mixed method
The above three have their own shortcomings, so we need to improve them.
function coder()
{
this .name = 'Modern Magic';
this.job = 'Programmer';
}
coder.prototype.coding = function(){
alert('I'm writing code');
};
Dynamic original chain
There is another way to solve the first three shortcomings.
function coder()
{
this .name = 'Modern Magic';
this.job = 'Programmer';
if (typeof(coder._init) == 'undefined')
{
this.coding = function ( :)