Javascript原型对象构造函数

时间:2013-10-27 10:39:35

标签: javascript

从“功能与面向对象的JavaScript开发”中获取此示例代码,但是获取了lastname未定义的错误?

根据我的理解,这篇文章说有一个原型初始化方法意味着如果我创建了许多Person,那么'initialize'方法只会在内存中存储一​​次,但是无法在下面运行。应该创建人并提醒姓氏吗?

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);

来自http://msdn.microsoft.com/en-us/magazine/gg476048.aspx的代码

1 个答案:

答案 0 :(得分:1)

你的代码错了

这样做:

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

而不是

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

一个方便的提示:在测试JS时保持控制台打开。节省一小时的调试时间。