Create javascript objects.
Information
Examples
<script type="text/javascript" language="JavaScript">
// 1. Create a Car 'class', using the function keyword.
// This function is also called the "constructor function"
function Car(type, wheels, doors, color, maxspeed) {
this.type = type;
this.doors = doors;
this.color = color;
this.wheels = wheels;
this.maxspeed = maxspeed;
}
// 2. Assign methods to the Car 'class' using the prototype keyword.
// With the prototype keyword you can add properties and methods
// The prototype property allows you to specify object properties
// outside the constructor function, which will be shared by all
// the objects instantiated from this function.
Car.prototype.changeMaxSpeed = function(maxspeed) {
this.maxspeed = maxspeed;
}
Car.prototype.changeColor = function(color) {
this.color = color;
}
// 3. Create a helper function
function showObjProp(obj) {
var str='';
for(var i in obj){
if(i=="type" || i=="doors" || i=="color" || i=="wheels" ||
i=="maxspeed" || i=="fuel") {
str += i+" = "+obj[i]+"\n";
}
}
alert(str);
}
// 4. Create mycar object by calling its constructor
mycar = new Car("limousine", 6, 4, "white", 60);
showObjProp(mycar);
// 5. Access mycar properties/methods using the dot operator
if(mycar.wheels == 6) {
mycar.changeMaxSpeed(100);
mycar.changeColor("red");
showObjProp(mycar);
}
// 6. Define a Truck 'class', the arguments must match the Car 'class'
function Truck(type, wheels, doors, color, maxspeed) {
this.type = type;
this.doors = doors;
this.color = color;
this.wheels = wheels;
this.maxspeed = maxspeed;
}
// 7. The Truck is a subclass of Car
Truck.prototype = new Car();
// 8. Add additional properties and methods to the Truck 'class'
Truck.prototype.fuel = "gas";
Truck.prototype.changeFuel = function(fuel) {
this.fuel = fuel;
}
// 9. Correct the constructor pointer because it points to Car
Truck.prototype.constructor = Truck;
// 10. Create a mytruck object by calling its constructor
mytruck = new Truck("truck", 8, 2, "black", 60);
showObjProp(mytruck);
// 11. Access mytruck methods using the dot operator
mytruck.changeMaxSpeed(200);
mytruck.changeFuel("diesel");
showObjProp(mytruck);
</script>
Show demo
|