Error :Uncaught TypeError: Object function

Error :Uncaught TypeError: Object function

本文关键字:function Object Uncaught Error TypeError      更新时间:2023-09-26

当我写book.main.method();时,我得到了错误:Uncaught TypeError: Object function () {

window.book = window.book|| {};
    book.control = function() {
        var check_is_ready = 'check_is_ready';
        if(check_is_ready == 'check_is_ready') {
            this.startbook = function() {
                var bookMain = new book.main();
                    bookMain.method();
            return;
            };
        };
    };
$(function() {
    var control = new book.control();
    control.startbook();
});
(function () {
    book.main = function() {     
    var index =0;
        this.method = function() {
            index++;
            if (index <= 500){
                book.main.method();//  <-- this wrong
                // the error which I get :Uncaught TypeError: Object function () { 
                alert (index);
                }
         };
    };
})();

我应该写什么代替book.main.method();调用它没有错误?

多谢

如果我理解正确的话,主要问题代码是:

(function () {
    book.main = function() {     
    var index =0;
        this.method = function() {
            index++;
            if (index <= 500){
                book.main.method();//  <-- this wrong
                // the error which I get :Uncaught TypeError: Object function () { 
                alert (index);
            }
         };
    };
})();

您正在尝试递归调用method()。执行递归调用的另一种方法是为函数表达式指定一个名称(methodFn)。只要记住这个名字只在函数体中有效:

(function () {
    book.main = function() {     
    var index =0;
        this.method = function methodFn() {
            index++;
            if (index <= 500){
                methodFn();
                alert (index);
            }
         };
    };
})();

您混淆了构造函数(book.main)和实例。

this.method = function() {将一个函数添加到new book.main()的实例中,而不是添加到book.main

我不确定你的最终目标,但你应该替换

book.main.method();//  <-- this wrong

this.method();//  <-- this works

还请注意,如果您希望看到递增的警报值,您必须切换两行:

(function () {
    book.main = function() {     
    var index =0;
    this.method = function() {
        index++;
        if (index <= 2){
            console.log(index); // less painful with console.log than with alert
            this.method();
        }
     };
    };
})();