(function(){
function IndexedDB(){
// 检测浏览器对indexedDB和web sql的支持
this.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB || false;
// IDBKeyRange 定义键的范围
this.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.mozIDBKeyRange || window.msIDBKeyRange || false;
this.webSQLSupport = ('openDatebase' in window);
this.db = null;
this.init();
}
IndexedDB.prototype = {
init : function(){
var _this = this;
_this.openDB();
_this.insertData();
},
openDB : function(){
var _this = this, request;
// 打开数据库
request = indexedDB.open("MyTestDatabase");
// 数据库打开后的回调函数
request.onsuccess = function(){
_this.db = request.result;
console.log(_this.db);
};
request.onerror = function(){
alert("Why didn't you allow my web app to use IndexedDB?!");
};
},
insertData : function(data){
var _this = this;
console.log(_this.db);
}
};
window.addEventListener('load', function(){
new IndexedDB();
}, false);
})();
代码如上,在openDB方法中的onsuccess回调里面,我已经获得了数据库的操作对象,并且赋值给了this.db,
但是为什么我在insertData方法中输出this.db却是null?貌似只能再其他回调里面才能执行,这个机制我不是很明白,请求大家给我科普下,感激不行!
因为onsuccess 是异步回调的,当你执行openDB的时候,并没有马上执行到onsuccess,然后你立刻就执行了insertData,这个时候,onsuccess并没有执行,所以this.db是null