闭包封装汽车对象

使用闭包封装一个汽车对象,可以获取汽车状态

var Car = (function(){
    var speed;
    function setSpeed(n){
        speed = n;
    }
    function getSpeed(){
        return speed;
    }
    function accelerate(){
        speed += 10;
    }
    function decelerate(){
        speed -= 10;
    }
    function getStatus(){
        if(speed>0){
            return 'running';
        }else{
            return 'stop';
        }
    }
    return {
        'setSpeed': setSpeed,
        'getSpeed': getSpeed,
        'accelerate':accelerate,
        'decelerate':decelerate,
        'getStatus':getStatus
    }
})();
    Car.setSpeed(30);
    Car.getSpeed(); //30
    Car.accelerate();
    Car.getSpeed(); //40;
    Car.decelerate();
    Car.decelerate();
    Car.getSpeed(); //20
    Car.getStatus(); // 'running';
    Car.decelerate(); 
    Car.decelerate();
    Car.getStatus();  //'stop';

你可能感兴趣的:(闭包封装汽车对象)