2012-03-14 108 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); 
    } 
}