This code is adapted from mozilla's intro to object oriented js page: Introduction to Object-Oriented JavaScript
When I run the following javascript code, I don't get the "hello" alert indicating that sayHello was called correctly. In the mozilla docs, the creation and calling of the person objects does not fall into an init function- which I copied into the bottom example. What gives?
window.onload = init();
function init()
{
var person1 = new Person('Male');
var person2 = new Person('Female');
// call the Person sayHello method.
person1.sayHello(); // hello
}
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.sayHello = function()
{
alert ('hello');
};
working example:
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.sayHello = function()
{
alert ('hello');
};
var person1 = new Person('Male');
var person2 = new Person('Female');
// call the Person sayHello method.
person1.sayHello(); // hello