Below in my code example there is an example of a getter and setter is this the proper way of using them in Javascript?
Question: Is this how to use a getter and setter in Javascript?
Code:
<body>
<p>Object</p>
<script>
function Car( model, year, miles ) {
this.model;
this.year = year;
this.miles = miles;
this.setmodel = function (m) {
if (do some checks here) {
this.model = m;
}
};
this.getmodel = function () {
return model;
};
this.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
}
Car.prototype.toAnotherString = function () {
return this.model + " has done " + this.miles + " miles";
};
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
console.log( civic.toString() );
console.log( mondeo.toString() );
console.log( civic.toAnotherString() );
console.log( mondeo.toAnotherString() );
alert(civic.toString());
</script>
</body>
</html>