所以我正在尝试使用 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')");
};
}
chrome 一直在大喊大叫:
Uncaught TypeError: Object #<MusicDAO> has no method 'openMainTable'
我有点困惑..我不能在函数内部创建之前调用函数吗?
最佳答案
没有。 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()
关于Javascript OOP 延迟调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21943508/