JavaScript Developer
JavaScript Developer

Reputation: 4008

JavaScript object has no method

I'm working on an application that uses JavaScript VERY heavily. I'm serializing JSON objects across pages, and I'm wondering if that is causing problems. If we ignore the serization, my code basically looks like this:

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

When I execute my "alert", I get an error that says:

"Object 0112-03-14T10:20:03.206Z has no method 'getFullYear'"

I can't figure out why I'm getting this error. I clearly have some object. However, I anticipate that it is some typing issue. Yet, I don't understand why. Is there a way to do a type check / cast?

Upvotes: 2

Views: 8204

Answers (4)

The Alpha
The Alpha

Reputation: 146269

currentDateTime = new Date(ud); should be currentDateTime : new Date(ud);

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

Which is the same as:

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

Upvotes: 0

kitti
kitti

Reputation: 14844

Try changing this:

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

to this:

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

Inside an object literal, you need to use : to map keys to values.

Upvotes: 4

pete
pete

Reputation: 25091

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

should be:

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

Upvotes: 2

jondavidjohn
jondavidjohn

Reputation: 62412

You have a syntax error in your this.data definition...

instead of

currentDateTime = new Date(ud);

make it...

currentDateTime : new Date(ud)

Otherwise your code copied to jsfiddle works

Upvotes: 1

Related Questions