Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a method on a specific instance?

Tags:

javascript

oop

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!

like image 667
Don Henton Avatar asked Jan 18 '26 20:01

Don Henton


2 Answers

You can just set the method for prius:

Prius.sellSelf = function() { return "I'm a snooty car with " + this.getMileage() + " mpg "; }
like image 178
SLaks Avatar answered Jan 20 '26 11:01

SLaks


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 = ...

like image 28
Rob W Avatar answered Jan 20 '26 11:01

Rob W