js中的面向对象.

Note:

 代码来自于亚马逊Ajax中.

function Vehicle() {

    var wheelCount = 4;

    var curbWeightInPounds = 4000;

 

    this.getWheelCount = function() {

        return wheelCount;

    }

 

    this.setWheelCount = function(count) {

        wheelCount = count;

    }

 

    this.getCurbWeightInPounds = function() {

        return curbWeightInPounds;

    }

 

    this.setCurbWeightInPounds = function(weight) {

        curbWeightInPounds = weight;

    }

 

    this.refuel = function() {

        return "Refueling Vehicle with regular 87 octane gasoline";

    }

 

    this.mainTasks = function() {

        return "Driving to work, school, and the grocery store";

    }

}

 

function SportsCar() {

    this.refuel = function() {

        return "Refueling SportsCar with premium 94 octane gasoline";

    }

 

    this.mainTasks = function() {

        return "Spirited driving, looking good, driving to the beach";

    }

}

 

function CementTruck() {

    this.refuel = function() {

        return "Refueling CementTruck with diesel fuel";

    }

 

    this.mainTasks = function() {

        return "Arrive at construction site, extend boom, deliver cement";

    }

}

 

function createInheritance(parent, child) {

    var property;

    for(property in parent) {

        if(!child[property]) {

            child[property] = parent[property];

        }

    }

}

 

 

function describe(vehicle) {

    var description = "";

    description = description + "Number of wheels (via property): "

                                                          + vehicle.wheelCount;

    description = description + "\n\nNumber of wheels (via accessor): "

                                  + vehicle.getWheelCount();

    description = description + "\n\nCurb Weight (via property): "

                                  + vehicle.curbWeightInPounds;

    description = description + "\n\nCurb Weight (via accessor): "

                                 + vehicle.getCurbWeightInPounds();

    description = description + "\n\nRefueling Method: " + vehicle.refuel();

    description = description + "\n\nMain Tasks: " + vehicle.mainTasks();

    alert(description);

}

 

function createVehicle() {

    var vehicle = new Vehicle();

    describe(vehicle);

}

 

function createSportsCar() {

    var sportsCar = new SportsCar();

    createInheritance(new Vehicle(), sportsCar);

    sportsCar.setCurbWeightInPounds(3000);

    describe(sportsCar);

}

 

function createCementTruck() {

    var cementTruck = new CementTruck();

    createInheritance(new Vehicle(), cementTruck);

    cementTruck.setWheelCount(10);

    cementTruck.setCurbWeightInPounds(10000);

    describe(cementTruck);

}

posted @ 2008-06-23 13:34  roboth  阅读(314)  评论(0)    收藏  举报