2013-10-27 63 views
1

得到了「功能與面向對象的JavaScript開發」這個例子的代碼,但得到錯誤姓氏是未定義?的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

回答

1

你的代碼是錯誤的

這樣做:

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

,而不是

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

和方便的提示:保持你的控制檯公開測試JS的時候。節省一小時的調試時間。

+0

大,工作:http://jsfiddle.net/NdLyA/9/ –

+0

所以我的理解正確,將只在內存中創建一次方法「初始化」,所以這是正確的/更好的方式來創建對象? –

+0

@ Dere_2929不一定是「更好」的方式,因爲它取決於案例。有很多方法可以在JS中創建對象。是的,該函數只創建一次,並在所有「Person」實例中共享。 – Joseph