So I've got this javascript class called Car and I've defined an instance of it, a Prius.
Car =
function Car ()
{
var mileage = 10;
var maker = "Basic";
var model = "Model";
return {
'sellSelf' : function() { return "I am a "+ model+ " from " + maker + " with mpg "+ mileage;} ,
'getMileage' : function() { return mileage; } ,
'setMileage' : function(m) { mileage = m; } ,
'getMaker' : function() { return maker; } ,
'setMaker' : function(m) { maker = m; } ,
'getModel' : function() { return model; } ,
'setModel' : function(m) { model = m; }
};
}
Prius = new Car();
Prius.setMaker('Toyota');
Prius.setModel('Prius');
Prius.setMileage(500);
alert(Prius.sellSelf());
alert(Prius.getMileage());
I'd like to be able to override sellSelf method for the Prius, to something like this:
function sellPrius() { return "I'm a snooty car with "+getMileage()+ " mpg "; }
Any suggestions, and am I right in saying that javascript is treating Car as 'abstract', Car.sellSelf() fails.
Thanks for the help!
You can just set the method for prius:
Prius.sellSelf = function() { return "I'm a snooty car with " + this.getMileage() + " mpg "; }
If you want to program in JS OOP, use prototype. The new prefix will only make sense for functions with a modified prototype, using this to access variables and methods. When you use new, the return value of a function is not returned. Instead, an instance of the class is returned, which equals to the this variable within that function.
The advantage of prototypes is that the functions are static, and only defined once. Hundred instances of the Car class will only have one, shared set of methods. When you use
Example:
function Car(){
//Optional: Default values
this.maker = "Unknown manufacture";
this.model = "Unknown model";
//NO return statement
}
Car.prototype.setMaker = function(maker){this.maker = maker}
Car.prototype.setModel = function(model){this.model = model}
//Et cetera
Car.prototype.getMaker = function(){return this.maker}
Car.prototype.getModel = function(){return this.model}
//Etc
Car.prototype.sellSelf = function(){return "Model: "+this.model+"\nMaker"+this.maker}
var Prius = new Car();
Prius.setMaker("Toyota")
Prius.setModel("Prius");
//Etc
alert(Prius.sellSelf());
Adding a new method can easily be done through setting Car.prototype.newMethod = function(){}. A huge advantage is proved: All instances of Car will now have this method, so you will only have to define the function once, instead of Prius.newMethod = ..; BMW.newMethod = ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With