[英]Calling function from another Javascript file and an object is said to be null
一個文字游戲源代碼放在文件 Main.js 中。
現在我正在嘗試添加另一個文件 Bookmarks.js(包含在 Main.js 文件之前的 web 頁面中),該文件將具有 object var bookmarks = {};
與本地存儲同步。
不幸的是,當我從 Main.js 調用 Bookmarks.js 中定義的函數時,我收到錯誤消息,指出書簽是 null:
這是錯誤消息的文本副本:
test?player=abcde:110 Uncaught TypeError: Cannot read property 'hasOwnProperty' of null
at getBookmark (test?player=abcde:110)
at updateBoard (test?player=abcde:244)
at setSelectedGid (test?player=abcde:159)
at rebuildMenu (test?player=abcde:197)
at WebSocket.ws.onmessage (test?player=abcde:151)
請幫助我理解,這怎么可能 - 因為bookmarks
變量設置在我的 Bookmarks.js 文件的最頂部:
'use strict';
// a map for local storage: game id -> obj with "words" and "total" properties
var bookmarks = {};
function saveBookmarks(games) {
for (var gid in bookmarks) {
// Javascript: skip any inherited properties
if (!bookmarks.hasOwnProperty(gid)) {
continue;
}
// if games obj does not have a property gid,
// then remove it from bookmarks obj as well
if (!games.hasOwnProperty(gid)) {
delete bookmarks[gid];
}
}
try {
window.localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
} catch (ex) {
console.log(ex);
}
}
function getBookmark(gid) {
if (
// if the bookmark for the game id is not found
!bookmarks.hasOwnProperty(gid) ||
!bookmarks[gid].hasOwnProperty('words') ||
!bookmarks[gid].hasOwnProperty('total')) {
// then return an empty object
bookmarks[gid] = {
words: '',
total: 0
};
}
return bookmarks[gid];
}
function updateBookmark(gid, words, total, games) {
if (
// if the bookmark for the game id is not found or
!bookmarks.hasOwnProperty(gid) ||
!bookmarks[gid].hasOwnProperty('words') ||
!bookmarks[gid].hasOwnProperty('total') ||
// the bookmark is found, but its total score is lower
total > bookmarks[gid]['total']) {
// then save a bookmark obj with new values
bookmarks[gid] = {
words: words,
total: total
};
// and update the local storage
saveBookmarks(games);
}
return bookmarks[gid];
}
jQuery(document).ready(function($) {
try {
bookmarks = JSON.parse(window.localStorage.getItem('bookmarks'));
} catch (ex) {
console.log(ex);
}
});
您使用以下命令覆蓋文件頂部定義的bookmarks
值:
jQuery(document).ready(function($) { try { bookmarks = JSON.parse(window.localStorage.getItem('bookmarks')); } catch (ex) { console.log(ex); } });
如果密鑰不存在, window.localStorage.getItem('bookmarks')
將返回null
。 然后JSON.parse(null)
將返回null
,然后將其分配給bookmarks
。
如果未在localStorage
中定義bookmarks
,請確保使用先前的值:
bookmarks = JSON.parse(window.localStorage.getItem('bookmarks')) || bookmarks;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.