Home > Web Front-end > JS Tutorial > JavaScript implements multiple method instances of classes_javascript skills

JavaScript implements multiple method instances of classes_javascript skills

WBOY
Release: 2016-05-16 17:34:53
Original
993 people have browsed it

Construction method

Copy code The code is as follows:

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
Copy code The code is as follows:

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

Copy code The code is as follows:

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:

Copy code The code is as follows:

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.

Copy code The code is as follows:

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.

Copy code The code is as follows:

function coder()
{
this .name = 'Modern Magic';
this.job = 'Programmer';
if (typeof(coder._init) == 'undefined')
{
this.coding = function ( :)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template