-2

当我写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();来调用它而不出错?

非常感谢

4

2 回答 2

0

您混淆了构造函数 ( 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();
        }
     };
    };
})();
于 2013-01-07T08:49:34.020 回答
0

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

(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);
            }
         };
    };
})();
于 2013-01-07T08:59:59.303 回答