0

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

1 Answer 1

3
window.onload = init();

There's your problem. This runs the init method, then applies the return value (undefined) as the onload property of the window. So nothing happens onload; everything happens immediately. This means that it happens before you modify Person.prototype.

Do this instead to delay execution:

window.onload = init;
Sign up to request clarification or add additional context in comments.

4 Comments

You also need to do that line after defining the init function, not before.
@DarkFalcon init is a function declaration, so will be hoisted.
Although I agree, it's best to declare functions at the top of their containing scope.
this works, and it seems to work whether or not that line lives before or after the init declaration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.