1

从“功能性与面向对象的 JavaScript 开发”中获得此示例代码,但收到未定义姓氏的错误?

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

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的代码

4

1 回答 1

1

你的代码错了

做这个:

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

代替

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

还有一个方便的提示:在测试 JS 时保持控制台打开。从一个小时的调试中拯救自己。

于 2013-10-27T10:45:03.747 回答