JavaScript Tutorial/Object Oriented/Constructor
Содержание
Class factory example
<source lang="javascript">
<html> <head> <title>Factory Example</title> </head> <body> <script type="text/javascript"> function createCar(sColor, iDoors, iMpg) {
var oTempCar = new Object; oTempCar.color = sColor; oTempCar.doors = iDoors; oTempCar.mpg = iMpg; oTempCar.showColor = function () { alert(this.color) }; return oTempCar;
} var oCar1 = createCar("red", 4, 23); var oCar2 = createCar("blue", 3, 25); oCar1.showColor(); oCar2.showColor();
</script> </body> </html></source>
Constructor Example
<source lang="javascript">
<html> <head> <title>Constructor Example</title> </head> <body> <script type="text/javascript"> function Car(sColor, iDoors, iMpg) {
this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.showColor = function () { alert(this.color) };
} var oCar1 = new Car("red", 4, 23); var oCar2 = new Car("blue", 3, 25); oCar1.showColor(); oCar2.showColor();
</script> </body> </html></source>
Constructor Paradigm
A class name is the name of the constructor.
A constructor "acts as" a factory function.
No object is created inside the constructor.
this keyword is used in constructor.
When a constructor is called with the new operator, an object is created before the first line of the constructor.
Constructors create a separate copy for each object.
<source lang="javascript">
function Car(sColor, iDoors) {
this.color = sColor; this.doors = iDoors; this.showColor = function () { alert(this.color) };
} var my1 = new Car("red", 4); var my2 = new Car("blue",3);</source>
Constructor prototype
<source lang="javascript">
<html> <head> <title>Example</title> </head> <body> <script type="text/javascript"> function Car(sColor, iDoors, iMpg) {
this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.owners = new Array("A", "B");
} Car.prototype.showColor = function () {
alert(this.color);
}; var oCar1 = new Car("red", 4, 23); var oCar2 = new Car("blue", 3, 25); oCar1.owners.push("C"); document.write(oCar1.owners); document.write(oCar2.owners); </script> </body> </html></source>
Object constructor
<source lang="javascript">
<html> <head> <script language="Javascript" type = "text/javascript">
</script> </head> <body> </body> </html></source>
Use Form input data to construct an object
<source lang="javascript">
<html> <head> <script language="Javascript" type = "text/javascript">
</script> </head> <body> <form name="Employeeform">
Employee Information</p>
Name: <input type="text" name="name" size="20">
Address: <input type="text" name="address" size="55">
Telephone: <input type="text" name="phone" size="20">
Email: <input type="text" name="email" size="20">
<input type="submit" value="Submit" OnClick="createEmployee()">
</form> </body> </html></source>