我在第一次尝试javascript oop时遇到了一个漩涡,我得到了一个错误:
uncaught typeerror:无法调用未定义的方法“addweight”
它抱怨的是weight.webdb.addWeight
下的一个方法正在从全局函数addWeight
调用。
var weight = {};
weight.webdb = {};
weight.webdb.db = null;
weight.webdb.addWeight = function() {
var db = weight.webdb.db;
db.transaction(function(tx) {
var addedOn = new Date();
tx.executeSql('INSERT INTO weight(input,comment,date) VALUES (?,?,?)', [inputWeight, inputComment, addedOn], weight.webdb.onSuccess, weight.webdb.onError);
});
};
function addWeight(){
var weight = document.getElementById('inputWeight');
var comment = document.getElementById('inputComment');
weight.webdb.addWeight(weight.value,comment.value);
}
演示:http://jsfiddle.net/SMbL3/1/
最佳答案
函数中定义的局部变量weight
正在外部作用域中隐藏weight
变量。只需调用函数局部变量,比如weight_elem
:
function addWeight() {
var weight_elem = document.getElementById('inputWeight');
var comment_elem = document.getElementById('inputComment');
weight.webdb.addWeight(weight_elem.value, comment_elem.value);
}