Javascript OOP延迟通话

时间:2014-02-21 19:30:14

标签: javascript oop google-chrome

因此我尝试使用javascript构建音乐播放器。 我使用以下代码创建了一个用于与Web数据库交互的DAO文件:

function MusicDAO()
{
    this.ins = openDatabase('musicDB', '1.0', 'MusicDB', 100 * 1024 * 1024);
    this.lastQueryResults = null;
    this.lastQueryError = null;
    this.openMainTable();

    this.openMainTable = function()
    {
        return this.execute("CREATE TABLE IF NOT EXISTS m_songs (file_id AUTO_INCREMENT, name, location, pic, genre)");
    };

    this.execute = function(query)
    {
        var instance = this;
        instance.ins.transaction(function(tx){
            tx.executeSql(query, [], function(e, results){
                instance.lastQueryResults = results;
            });
        }, function(e){
            console.log("error", e);
            instance.lastQueryError = e;
        });

        return instance.lastQueryResults;
    };

    this.addSong = function(){
        return this.execute("INSERT INTO m_songs" +
            "(name, location, pic, genre)" +
            "VALUES" +
            "('menahem', '/pla', null, 'trance')");
    };
}

并且铬一直在喊这个:

Uncaught TypeError: Object #<MusicDAO> has no method 'openMainTable' 

我有点困惑..我不能在函数内部创建之前调用函数吗?

3 个答案:

答案 0 :(得分:3)

不。 Javascript是一种解释型语言,而不是编译语言。由于解释器尚未到达您声明函数的行,因此该函数尚不存在。

现在,这并不意味着在调用它们之前无法定义函数。您可以;你不能按照你写的方式去做。这是一个我希望澄清事情的例子:

function TestFunctions() {
    // Works
    fn();

    try {
        // Does not work
        this.fnFromExpression();
    } catch (ex) {
        console.log('caught exception');
    }

    function fn() {
        console.log('inside fn()');
    }

    this.fnFromExpression = function() {
        console.log('inside fnFromExpression()');
        // do something
    };

    // now it works
    this.fnFromExpression();
}

new TestFunctions();

控制台输出将是:

inside fn()
caught exception
inside fnFromExpression()

答案 1 :(得分:2)

不,不是这样。您可以将这些方法添加到MusicDAO的原型中,然后让MusicDAO()成为构造函数。

答案 2 :(得分:2)

您可以尝试将这些方法放在原型上:

function MusicDAO()
{
    this.ins = openDatabase('musicDB', '1.0', 'MusicDB', 100 * 1024 * 1024);
    this.lastQueryResults = null;
    this.lastQueryError = null;
    this.openMainTable();    
}

MusicDAO.prototype.openMainTable = function()
{
    return this.execute("CREATE TABLE IF NOT EXISTS m_songs (file_id AUTO_INCREMENT, name, location, pic, genre)");
};

MusicDAO.prototype.execute = function(query)
{
    var instance = this;
    instance.ins.transaction(function(tx){
        tx.executeSql(query, [], function(e, results){
            instance.lastQueryResults = results;
        });
    }, function(e){
        console.log("error", e);
        instance.lastQueryError = e;
    });

    return instance.lastQueryResults;
};

MusicDAO.prototype.addSong = function(){
    return this.execute("INSERT INTO m_songs" +
        "(name, location, pic, genre)" +
        "VALUES" +
        "('menahem', '/pla', null, 'trance')");
};

关于这一点的好处是,如果你创建了很多MuscDAO实例(你可能不会这样做),那么这个方法在每个实例中都不会重复。