简体   繁体   中英

Javascript Prototype Object Constructor

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM