I am trying to maximize the reuse of some code. On my custom javascript object (I'll use PhoneNumber as an example for the sake of simplicity), I am setting a prototype function like this:
var Map = {
write: function() {
alert('My object is ' +this);
}
};
function PhoneNumber(number) {
this.number = number;
}
PhoneNumber.prototype = Map;
//I can call the write function like so
var phoneObject = new PhoneNumber('1234567894');
phoneObject.write(); //ALERT My Object is Object{number:'1234567894'}
Everything works fine except for the fact that for some reason it turns my Phone Number object into a generic Object instead of keeping its PhoneNumber constructor. If I actually place the write function inside the objects prototype like this, it works perfectly.
function PhoneNumber(number) {
this.number = number;
}
PhoneNumber.prototype.write = function() {
alert('My object is ' +this);
}
var phoneObject = new PhoneNumber('1234567894');
phoneObject.write(); //ALERT My object is PhoneNumber{number:'1234567894'}
But I'd really rather not have to do it this way because multiple objects use the write function and they all perform the exact same way. How can I avoid my objects converting themselves into generic constructors? Apparently I'm setting the Map object on the prototype the wrong way, but its quite important that I not have to copy the code directly from Map into the object prototype function. Any ideas?
You forgot to set PhoneNumber.prototype.constructor
When you do PhoneNumber.prototype = Map
you destroy the constructor property
PhoneNumber.prototype = Map;
PhoneNumber.prototype.constructor = PhoneNumber;
Of course that won't work because your just doing Map.constructor = PhoneNumber
which breaks if you use Map
as multiple prototypes. So you should just have PhoneNumber inherit from map
PhoneNumber.prototype = Object.create(Map, {
constructor: { value: PhoneNumber }
});
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