JavaScript对象没有方法

JavaScript object has no method

本文关键字:有方法 对象 JavaScript      更新时间:2023-09-26

我正在开发一个大量使用JavaScript的应用程序。我正在跨页面序列化JSON对象,我想知道这是否会导致问题。如果我们忽略序列化,我的代码基本上是这样的:

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.206Z没有方法'getFullYear'"

我不明白为什么我会犯这个错误。我显然有一些反对意见。然而,我预计这是一些打字问题。然而,我不明白为什么。有没有方法进行类型检查/强制转换?

尝试更改此项:

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

到此:

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

在对象文字中,需要使用:将键映射到值。

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

应该是:

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

您的this.data定义中存在语法错误。。。

而不是

currentDateTime = new Date(ud);

让它…

currentDateTime : new Date(ud)

否则,复制到jsfiddle的代码将运行

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