Patrioticcow
Patrioticcow

Reputation: 27038

how to fix undefined property in javascript?

i have this script:

var Tord = (function () {

    Tord.prototype.getHeader = function () {
        alert('test');
    };

    return Tord;
})();

$(document).ready(function() {

    var tod = new Tord();
    tod.getHeader();
});

i get an error Uncaught TypeError: Cannot read property 'prototype' of undefined line 3

i don't understand why?

here is how my js files are loaded:

    <link rel="stylesheet" href="public/jquery.mobile/jquery.mobile-1.2.0.min.css" />
    <link rel="stylesheet" href="public/style.css" />
    <script src="public/jquery-1.8.3.min.js"></script>
    <script src="public/jquery.mobile/jquery.mobile-1.2.0.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="public/cordova-2.2.0.js"></script>
    <script type="text/javascript" charset="utf-8" src="public/script.js"></script>

script.js has the script from above.

any ideas? thanks.

Upvotes: 2

Views: 4632

Answers (1)

raina77ow
raina77ow

Reputation: 106385

Because of exactly the code you've shown. Look, when this line is invoked...

Tord.prototype.getHeader = function () {

... Tord is undefined. But Tord should be a function when you set this (as prototype should be a property of constructor function to be of any use) - and you don't make any efforts to make Tord a function at all.

I think what you want to do may be achieved with this:

var Tord = (function () {
    var Tord = function() {}; // to properly name the constructor
    Tord.prototype.getHeader = function () {
        alert('test');
    };
    return Tord;
})();

With this you can define different constructors based on some external logic (but still define them once). But in the current state of your code there's no need to make it that complex: this...

var Tord = function() {};
Tord.prototype.getHeader = function() { ... };

... should suffice, in my opinion.

Upvotes: 7

Related Questions