How to implement validation with encapsulation

2019-09-16 14:46发布

问题:

Please first see original question: Encapsulation in JavaScript with getter and setter

@Jacob Thanks Jacob! That is great information.I am not quite sure how that solution works but placing the methods into that return clause works well. Here is my working Class definition:

function vehicle(thewheels, thecolour){
    var colour=thecolour;
    var wheels=thewheels > 4 ? '4' : thewheels;
    return {
            getcolour: function() {
            return colour; 
        },
            setcolour: function(value) { 
            colour = value;
        },
            getwheels: function() {
            return wheels; 
        },
            setwheels: function(value) { 
            wheels = value;
        }
    }
} 

I have put some code into the constructor (presumably it could be more complex code) to process input data. I could place the same code into the 'setwheels' method in order to fully 'gate-keep' the data coming in; BUT surely there must be a simpler way of managing the input data without having to duplicate that code?

I tried placing this new function into the Class definition:

setwheels: function(value) { 
    wheels = validwheels(value);
},
validwheels: function(wheelsin){
    return wheelsin > 4 ? 4 : wheelsin;
}

But the constructor could not see that 'validwheels' function. Is there any way of re-using validation code for instantiation and 'setting' in this class?

回答1:

Here is a complete solution demonstrating encapsulation and validation. Thanks go to @Jacob and @evolutionxbox for their great assistance!

     <button onclick="testOOP()">Click me</button>

     <script>
       //<!-- 
       function testOOP(){
        var v1 = new vehicle(40, "red"); //setting new values during instantiation
        var v2 = new vehicle(2, "blue");
        showVehDetails(v1);
        showVehDetails(v2);
        v2.wheels=10;           //validated input restricted to 4
        showVehDetails(v2);
        v2.colour="orange";     
        showVehDetails(v2);
        }

        function showVehDetails(v){
            document.write("This vehicle is " + v.colour + " and has " + v.wheels + " wheels.<br/>");
        }

        //*************'vehicle' - Class definition**************
function vehicle(thewheels, thecolour){
    var colour=thecolour;
    var wheels=validWheels(thewheels);
    function validWheels(wheelsin){
        return wheelsin > 4 ? 4 : wheelsin;
    }
    return {
            get colour() {
            return colour; 
        },
            set colour(value) { 
            colour = value;
        },
            get wheels() {
            return wheels; 
        },
            set wheels(value) { 
            wheels = validWheels(value);
        }
    }
} 
        //************End class definition************************
       //-->
     </script>