Home > Web Front-end > JS Tutorial > body text

JavaScript common object class creation code and analysis of advantages and disadvantages_js object-oriented

WBOY
Release: 2016-05-16 18:40:06
Original
1158 people have browsed it

There are several ways to build a class in Javascript:
1.Factory method

Copy code The code is as follows:

function createCar(){
var car = new Object();
car.color="b";
car.length=1;
car.run=function(){alert(”run”);}
return car;
}

After defining such a function, you can use:
var car1 = createCar();
var car2 = createCar();
to create a new object. The problem with this method is that every time a car object is created, the run Function must be re-created. It is a waste of memory.

2.Constructor method
Copy code The code is as follows:

function Car(){
this.color=”b”;
this.length=1;
this.run=function(){alert(”run”);}
}
var car1=new Car();
var car2=new Car();

This is the most basic method, but it also has the same problems as the factory method

3.prototype method
Copy code The code is as follows:

function Car(){
}
Car.prototype.color=”b”;
Car.prototype.length=1;
Car.prototype.run=function(){alert ("run");
}

The disadvantage of this method is that when this class has a reference attribute, changing this attribute of one object will also change the attributes of other objects
For example:
Copy code The code is as follows:

Car.prototype.data1=new Array() ;
var car1=new Car();
var car2=new Car();
car1.data1.push("a");

At this time, car2 .data also contains the "a" element

4. Prototype/Constructor hybrid method [Commonly used]
Copy code The code is as follows:

function Car(){
this.color=”b”;
this.length=1;
this .data1=new Array();
}
Car.prototype.run=function(){
alert("dddd");
}


This kind This method eliminates those shortcomings. It is currently a widely used method

5. Dynamic prototype method [commonly used]
Copy Code The code is as follows:

function Car(){
this.color="b";
this.length=1;
this.data1=new Array();

if(typeof Car.initilize==”undefined”){
Car.prototype.run=function(){alert(”a”);}
}

Car.initilize=true;
}

Among these methods, the most commonly used are hybrid prototype/constructor and dynamic prototype methods
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