简体   繁体   中英

JavaScript not Assigning to Global Variable

I have the following code, which will return the login name for the currently logged-in SharePoint user :

var currentUser;
var currentUserName;
ExecuteOrDelayUntilScriptLoaded(MainMethod,'sp.js');

function MainMethod() {
    GetName();
    alert("MAIN " + currentUserName);
}

function GetName(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
function onQuerySucceeded() {
    currentUserName= currentUser.get_loginName().split("\\")[1];
    alert("GetName " + currentUserName);
}
function onQueryFailed(sender, args) {
    alert('Failed to retrieve user name');
}

When I run the code, I get these 2 alert message boxes :

"GetName" firstname.lastname

"MAIN" undefined

Shouldn't the line currentUserName= currentUser.get_loginName().split("\\\\")[1]; assign the firstname.lastname value to the global currentUserName variable?

You can make sure that you're accesing global property by using window.currentUserName = currentUser.get_loginName().split("\\\\")[1] .

To avoid polluting global namespace with many variables you can group them in an object like this:

window.user = {
    currentUserName,
    currentUser
}

Then you could access it by window.user.currentUserName .

Use alert("MAIN " + currentUserName); in success() function. It will get the changed value, but not in MainMethod() because jsom executing asynchroneously.

  • It will first execute GetName() function
  • Then it will execute the alert("MAIN " + currentUserName);
  • Then it will execute onQuerySucceeded()

That's why you are getting undefined for MAIN because MAIN is executing before the success() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM