简体   繁体   English

如何在javascript中修复未定义的属性?

[英]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 我得到一个错误Uncaught TypeError: Cannot read property 'prototype' of undefined第3行的Uncaught TypeError: Cannot read property 'prototype' of undefined

i don't understand why? 我不明白为什么?

here is how my js files are loaded: 这是我的js文件的加载方式:

    <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. script.js有上面的脚本。

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. 但是当你设置它时,Tord应该是一个函数(因为prototype应该是构造函数的一个属性才有用) - 并且你没有做任何努力使Tord成为一个函数。

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. ......在我看来,应该足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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