This question already has an answer here:
- How does JavaScript .prototype work? 12 answers
As I understand, in JavaScript every object has a prototype
and it exposes some default properties. I have the following code where I'm trying to set the Year property of two objects through prototype
. But both the calls are failing.
How can I override toLocalString()
for any object if I don't have access to the prototype
? Please note that the following code is to test on the prototype
property, but my intention is to override the toLocalString()
method.
var car = {
Make: 'Nissan',
Model: 'Altima'
};
car.Year = 2014;
alert(car.Year);
alert(car.prototype); // returns undefined
car.prototype.Year = 2014; // Javascript error
// --------------
function Car() {
this.Make = 'NISSAN';
this.Model = 'Atlanta';
}
var v = new Car();
v.prototype.Year = 2014; // JavaScript error
alert(v.prototype);
Car.prototype.Year = 2014
- you set the prototype on the object function - not the created instance. – tymeJV Oct 1 '14 at 19:49toLocaleString()
instead oftoLocalString()
or do you want to implement your own methodtoLocalString()
? – pasty Oct 1 '14 at 20:02prototype
property belongs on a function. The function uses thatprototype
property when called withnew
to construct instance objects. Settingprototype
on a non-function object has no effect. – apsillers Oct 1 '14 at 20:15