tags:

views:

102

answers:

2

I would like to add isBlack method to Car only if this method is not already present. At the bottom of the page I have done that by checking for both in prototype and in the Car object itself. I was wondering if there is a better way to handle the case. I don't like the double check.

Note that isBlack method might come to Car from Car itself or through prototype.

function Vehicle(name){
  this.name = name;
};

Vehicle.prototype.tyres = 4;

function Car(){}

Car.prototype = new Vehicle();

Car.prototype.constructor = Car;

if !(Car.isBlack || Car.prototype.isBlack){
   Car.prototype.isBlack = 'false';
}
A: 

The double check is probably as good as it's going to get. The alternative would be instancing a Car and checking for isBlack in it, which is quite a waste.

chaos
+1  A: 

As long as you are going the full prototype route and thus you must be creating these such that they can be safely constructed without side effects (which you need to do to create an instance of each to use as a prototype of sub-types), you could just test it on such an instance.

if (!(new Car()).isBlack) {
    Car.prototype.isBlack = 'false';
}
ironfroggy