简体   繁体   中英

JavaScript Variable Undefined, but it is not

So I have the following JavaScript which pulls user data from Facebook:

在此处输入图片说明

As you can see in that snippet I have included the line 'console.log(full_name);', which when ran successfully outputs the users full name into the browser console.

Then when I try this:

<script>document.write('Hello, ' + full_name);</script>

It doesn't work. It comes back with Uncaught ReferenceError: full_name is not defined .

I am confused as it is clearly defined & works when using console.log . Someone help?

<script>document.write('Hello, ' + full_name);</script>

您没有定义全局变量full_name。

It definitely would throw an error.

Assuming that you are including the line

<script>document.write('Hello, ' + full_name);</script>

in the HTML directly, it will be executed much before the call getLoginStatus of fb API completes, which is where you have defined the global variable full_name

Not to mention this is a bad practice (Declaring global variables), but it is.

In your example, invoking console.log(full_name) works because it's defined within that code. Referencing full_name in the inline script you specified won't work as it can't access the scope of the callback you pass to getLoginStatus ; more specifically, in your example, it will look for full_name on the global object, which is window in the case of the browser. Thus, window.full_name is correctly undefined . In any case, there's also no guarantee that your callback will have been invoked by the time you invoke document.write .

To remedy this, you'll need to call document.write within your callback or store the value elsewhere for later retrieval. As an aside, you should avoid document.write .

Smashing Magazine has an article on JavaScript scope.

It seems you are trying to render the name on the page. However, as @Andreas pointed out the document.write is executed as soon as that block is hit, which is before your Facebook API call is returned. Instead, try placing an id on the element you want the name to be rendered in and use getElementById within your callback. Something like this.

FB.api('/me', function(response) {
  document.getElementById('name').innerHTML = response.name;
});

Also, as others have mentioned, you are polluting your global scope with many variables by placing them within your call back without the var keyword.

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