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 enumerable by default. So if you're using ES5, 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
myApp.model.Person.prototype
only add those functions to thePerson
objects that are a part of yourmyApp.model
, and not allPerson
objects? If that is intended, that's fine. I could just see that becoming an issue later on. Do you have a separatePerson
object? \$\endgroup\$myApp.model
as my package, the fully qualified class name I want to make ismyApp.model.Person
. This class shall have a constructor that take Stringname
as parameter, and have 2 methodssayName
andsayHi
. It is simple to be achieved in Java, but I am not sure how to make it right in Javascript. \$\endgroup\$Person
object. Why it could be an issue if I define my qualified class name asmyApp.model.Person
? \$\endgroup\$Person
constructor is stored, whether it'smyApp.model.Person
or anywhere else. AllPerson
instances which share that constructor will have access to the functions attached to the constructor'sprototype
. \$\endgroup\$