When you assign an object to a prototype it changes the prototypal inheritance of that object. The prototype of the object will no longer have the original constructor function and it will point to Object
instead!
This affects your code, as it is evidenced by adding the following line:
console.log(p1.constructor === Object); // returns: true
Two ways to correct this:
A. Assign the functions directly. Don't wrap them in an object. That would look like this:
myApp.model.Person.prototype.sayName = function(){
alert(this.name);
};
myApp.model.Person.prototype.sayHi = function(){
alert("Hi, " + this.name);
};
B. Reassign the constructor to your object. You can do that by adding a line of code into your object, like this:
myApp.model.Person.prototype = {
constructor: myApp.model.Person, // <========
sayName: function () {
alert(this.name);
},
sayHi: function () {
alert("Hi, " + this.name);
}
};
Which is the same as this:
myApp.model.Person.prototype.constructor = myApp.model.Person;
It's worth noting that restoring the constructor in this manner creates a property with enumerable
set to true
. Native constructors are not not enumerable by default. So if you're using ES5, you can do this might be the preferred way to restore the constructor:
Object.defineProperty(myApp.model.Person.prototype, 'constructor', {
enumerable: false,
value: myApp.model.Person
});
More reading on this: http://javascript.info/tutorial/constructor