You should be assigning getInfo
in only one place. Either in the prototype or in the constructor (preferably prototype), but NOT both places.
If you do both, the one assigned in the constructor will take precedence because it is assigned to the actual object which is searched first (before the prototype is searched). The prototype is only used if there is no property with the desired name already attached directly to the object. Because you've assigned a .getInfo
property directly to the object in the constructor, the prototype is not searched when resolving that property name (because it's already found).
Since your code indicates that you think the .prototype
version is the override, it appears that you just have that logic backwards. The getInfo()
assigned to the object in the constructor is what overrides the prototype.
If you truly wanted to execute the prototype version, you could access it directly on the prototype:
Vehicle.prototope.getInfo.call(car1);
But, really if you want access to both methods, you should just given them different names so they are both accessible as car1.method1()
and car1.method2()
.
So to summarize from your specific questions:
1- Despite providing the definition of Vahicle.prototype.getInfo(), why the car1.getInfo() will be invoked? ( the local copy not the generic one?) why it ie being ignored?
The object itself is searched before the prototype so the getInfo assigned directly to the object in the constructor will be found by the interpreter first and the prototype will not be searched.
2-How can I invoke the car1.prototype.getInfo())? If I call it like car1.prototype.getInfo().call the interpreter says: Unable to get property 'getInfo' of undefined or null reference
The best solution is to give the two functions different names so they are both callable in the conventional way. If you absolutely have to call the prototype version, you can do so as Vehicle.prototope.getInfo.call(car1);
.
One might ask, why are you giving these two functions the same property name? That's what is creating the problem in the first place.