简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM