我們已經有一個全局變量可用。我們如何直接在jQuery對象上創建變量。然後,在我們的各種功能中,我們可以簡單地檢查它們是否存在,如果它們不存在,那麼執行它們,或者如果它們存在,則參考它
看着你的小提琴,這也可以非常輕鬆地完成 - 只需讓每個需要訪問全局命名空間的函數創建或引用它即可。
$(function() {
$.bob_jsNS = $.bob_jsNS || {};
var mainurl = 'http://localhost:9000';
/* Login User */
$("#submit-login").click(function() {
userLogin();
});
function userLogin() {
$.bob_jsNS.user = $.bob_jsNS.user || {};
var myUser = $.bob_jsNS.user;
myUser.userName = $('#user').val();
var password = $('#pass').val();
// var data = $("#login-user").serialize();
var data = {
"userName": myUser.userName
}
$('#sdlc-gif').show();
// I simply reference the global namespace to get the userName.
if (myUser.userName != '' && password != '') {
// Removed for clarity. There was code here.
}
}
function requestDemo() {
/*****
* Any time I need access to any part of the global namespace,
* I should first check that it's there -- and if not, create it.
* These first few lines happen on any function that will need to get
* or set global values or functions.
***/
$.bob_jsNS = $.bob_jsNS || {};
$.bob_jsNS.user = $.bob_jsNS.user || {};
var myUser = $.bob_jsNS.user;
// If we don't have a username, set it blank.
// May not be an issue, but it may break otherwise.
var myUser.userName = myUser.userName || "";
var myUser.first = ('#firstName').val();
var myUser.last = ('#lastName').val();
var myUser.title = ('#jobTitle').val();
var myUser.email = ('#email').val();
var myUser.comments = ('#comments').val();
var myUser.app1 = ('#app1').val();
var myUser.app2 = ('#app2').val();
var myUser.app3 = ('#app3').val();
var data = {
"userName": myUser.userName,
"firstName": myUser.first,
"lastName": myUser.last,
"jobTitle": myUser.title,
"email": myUser.email,
"comments": myUser.comments,
"app1": myUser.app1,
"app2": myUser.app2,
"app3": myUser.app3
}
/***
* More code was here, abbreviated for clarity.
***/
}
/* Provide feedback form */
$("#submit-feed").click(function() {
provideFeedback();
});
/* Provide Feedback */
function provideFeedback() {
// var data = $("#provide-feed").serialize();
$.bob_jsNS = $.bob_jsNS || {}
$.bob_jsNS.user = $.bob_jsNS.user || {};
var userName = $.bob_jsNS.user.userName || "";
var q1 = $("input[name='group1']:checked").val();
var q2 = $("input[name='group2']:checked").val();
var q3 = $("input[name='group3']:checked").val();
var q4 = $("#ans4").val();
var q5 = $("#ans5").val();
var data = {
"userName": userName,
"q1": q1,
"q2": q2,
"q3": q3,
"q4": q4,
"q5": q5
}
}
});
依靠這樣的全局變量通常是不好的做法。你的問題的答案確實如下所述使用窗口對象,但我建議考慮重新考慮你組織上述的方式,以避免需要使用全局範圍。例如,爲什麼你甚至需要將範圍分離到這兩個函數中?或者,你可以將用戶名傳遞給requestDemo(用戶名)嗎? –