1

Got this example code from 'Functional vs. Object-Oriented JavaScript Development' but get error that lastname is undefined?

From my understanding this article is saying that having a prototype initialize method will mean that the method 'initialize' is only stored once in memory if I create many Person's, but cant get below to run. Should create person and alert the lastname?

http://jsfiddle.net/NdLyA/4/

    // Pseudo constructor
var Person = function(name, lastname, birthdate) 
{
    this.initialize(name, lastname, birthdate);
}

// Members
Person.prototype.initialize(name, lastname, birthdate)
{
    this.Name = name;
    this.LastName = lastname;
    this.BirthDate = birthdate;
}
Person.prototype.getAge = function()   
{
    var today = new Date();
    var thisDay = today.getDate();
    var thisMonth = today.getMonth();
    var thisYear = today.getFullYear();
    var age = thisYear-this.BirthDate.getFullYear()-1;
    if (thisMonth > this.BirthDate.getMonth())
        age = age +1;
    else 
       if (thisMonth == this.BirthDate.getMonth() &&
           thisDay >= this.BirthDate.getDate())
           age = age +1;
    return age;
}

var jon = new Person('Jon','Smith', null);
alert(jon.Name);

Code from http://msdn.microsoft.com/en-us/magazine/gg476048.aspx

1 Answer 1

1

Your code was wrong

Do this:

// Members
Person.prototype.initialize = function(name, lastname, birthdate) {

instead of

// Members
Person.prototype.initialize(name, lastname, birthdate){

And a handy tip: Keep your console open when testing JS. Save yourself from an hour of debugging.

Sign up to request clarification or add additional context in comments.

2 Comments

so is my understanding correct that the method 'initialize' will only be created once in memory so this is the correct/better way to create objects?
@Dere_2929 Not necessarily the "better" way, because it depends on the case. There are a lot of ways to create objects in JS. And yes, the function is created once, and shared across all instances of Person.

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.