JavaScript (1) Object Basics

1. Defining a Class or Object
  1.1 Mixed Constructor/Prototype Methods
    Use a constructor to define all non-functional properties of an object, similar to Java's constructor. Use prototype methods to define functional properties (methods) of an object. This method is to use a relatively broad method of defining a class or object.

1  // Mixed Constructor/Prototype 
2  // Define all non-functional properties of an object with a constructor 
3  function Car(sColor, iDoors, iMpg){
 4      this .color = sColor;
 5      this .doors = iDoors
 ;      this .mpg = iMpg;
 7      this .drivers = new Array("Mike", "Sue" );
 8  }
 9  
10  // Define the function properties (methods) of the object with the prototype method, and only create an instance of the showColor() function , will not waste memory space 
11 Car.prototype.showColor = function (){
 12      alert( this .color);
 13 }
 14  
15  var oCar1 = new Car("red", 4, 23 );
 16  var oCar2 = new Car("blue", 3, 25 );
 17  
18  // The values ​​of oCar1, oCar2 properties do not affect each other, and can An example of a shared showColor() function 
19 oCar1.drivers.push("Matt" );
 20 document.write(oCar1.color + "," + oCar1.doors + "," + 
 21      oCar1.mpg + "," + oCar1.drivers + "</br>");         // Output: red,4,23,Mike,Sue,Matt 
22 document.write(oCar2.color + "," + oCar2.doors + "," + 
 23      oCar2 .mpg + "," + oCar2.        drivers + "</br>");        //Output: blue,3,25,Mike,Sue

 

//Mixed constructor/prototype method
//Define all non-functional properties of an object with a constructor
function Car(sColor, iDoors, iMpg){
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");
}

//Define the function property (method) of the object with the prototype method, only create an instance of the showColor() function, and will not waste memory space
Car.prototype.showColor = function(){
alert(this.color);
}

var oCar1 = new Car("red", 4, 23);
var oCar2 = new Car("blue", 3, 25);

//The values ​​of oCar1, oCar2 attributes do not affect each other, and can share an instance of the showColor() function
oCar1.drivers.push("Matt");
document.write(oCar1.color + "," + oCar1.doors + " ," +
oCar1.mpg + "," + oCar1.drivers + "</br>"); //Output: red,4,23,Mike,Sue,Matt
document.write(oCar2.color + "," + oCar2.doors + "," +
oCar2.mpg + "," + oCar2.drivers + "</br>"); //Output: blue,3,25,Mike,Sue

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325706893&siteId=291194637