I realise that this has been asked but have researched and failed - sorry!
I want to implement encapsulation in JS as simply as possible. I realise that any 'var' in the class will be private.
I am simply unsure how to GET and SET values of any private var. In the example below the interface methods for GETTING and SETTING 'colour' do not work because those functions cannot access the private 'colour' property of the object. I cannot find a clear example showing me how to implement this.
I am not even sure that using '.prototype' is the best way to add those methods to the class.
Thank you!
<button onclick="testOOP()">Click me</button>
<script>
//<!--
function testOOP(){
var v1 = new vehicle(4, "red"); //setting new values during instantiation
var v2 = new vehicle(2, "blue");
showVehDetails(v1);
showVehDetails(v2);
v2.wheels=1; //demonstrating no encapsulation
showVehDetails(v2);
v2.setcolour("orange"); //using an interface - fails
showVehDetails(v2);
}
function showVehDetails(v){
document.write("This vehicle is " + v.getcolour() + " and has " + v.getwheels() + " wheels.<br/>");
}
//*************'vehicle' - Class definition**************
function vehicle(thewheels, thecolour){
this.wheels = thewheels; //public property
var colour = thecolour; //private property
}
vehicle.prototype = {
constructor: vehicle,
getcolour: function(){
return this.colour; //but how to create a GETTER for colour?
},
getwheels: function(){
return this.wheels;
},
setwheels: function(newwheels){
this.wheels = newwheels;
},
setcolour: function(newcolour){ //and how to create a SETTER for colour?
this.colour = newcolour;
}
}
//************End class definition************************
//-->
</script>