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?
Here is a complete solution demonstrating encapsulation and validation. Thanks go to @Jacob and @evolutionxbox for their great assistance!