2012-03-14 110 views
2

我正在使用JavaScript的應用程序非常繁重。我在跨頁面序列化JSON對象,我想知道是否會導致問題。如果我們忽略serization,我的代碼基本上是這樣的:JavaScript對象沒有方法

function MyClass() { this.init(); } 
MyClass.prototype = { 
    init: function() { 
      var cd = new Date(); 
      var ud = Date.UTC(cd.getYear(), cd.getMonth(), cd.getDate(), cd.getHours(), cd.getMinutes(), cd.getSeconds(), cd.getMilliseconds()); 

     this.data = { 
      currentDateTime = new Date(ud); 
     } 
    } 
} 

try { 
    var myClassInstance = new MyClass(); 
    alert(myClassInstance.data.currentDateTime.getFullYear()); 
} catch (e1) { 
    console.log(e1); 
} 

當我執行我的「警報」,我得到一個錯誤,指出:

「對象0112-03-14T10:20:03.206 Z沒有方法'getFullYear'「

我想不通爲什麼我得到這個錯誤。我清楚地有一些對象。不過,我預計這是一些打字問題。然而,我不明白爲什麼。有沒有辦法進行類型檢查/轉換?

+0

只是要清楚:你不能序列化JSON。 JSON已經是數據的文本表示。你可能意味着你正在序列化JavaScript對象。此外,你的代碼甚至不應該給你那個錯誤,因爲'currentDateTime = new Date(ud);'是無效的JavaScript。如果你解決了這個問題,它可以工作:http://jsfiddle.net/yTVmj/ – 2012-03-14 14:31:25

+0

在這個環境下,'this'指的是什麼。你可能需要傳入對象的內容 – Michael 2012-03-14 14:31:51

+1

@Michael:'this'指的是'this.in'在'this.init()'中引用的內容。如果用'new MyClass()'調用(如在代碼中完成的那樣),那將是一個從'MyClass.prototype'繼承的空對象。 – 2012-03-14 14:35:03

回答

4

嘗試修改此:

this.data = { 
    currentDateTime = new Date(ud); 
} 

這樣:

this.data = { 
    currentDateTime: new Date(ud) 
} 

內的對象文本,你需要使用:到鍵映射到值。

+1

從行尾刪除分號(;)。 – 2012-03-14 14:39:15

+0

@SheikhHeera哎呀!錯過了那個,謝謝! – 2012-03-14 14:40:18

+0

歡迎並沒有問題,我們都很着急。 :-) – 2012-03-14 14:42:29

1

您的this.data定義一個語法錯誤...

,而不是

currentDateTime = new Date(ud); 

使其...

currentDateTime : new Date(ud) 

否則你的代碼複製到的jsfiddle works

2
this.data = { 
    currentDateTime = new Date(ud); 
} 

應該是:

this.data = { 
    currentDateTime: new Date(ud) 
} 
0

currentDateTime = new Date(ud);應該currentDateTime : new Date(ud);

this.data = { 
    // Initialize as a property 
    currentDateTime : new Date(ud) 
} 

這是一樣的:

this.data = { 
    currentDateTime: function() { 
     return new Date(ud); 
    } 
}