Ydhem
Ydhem

Reputation: 928

Javascript : var scopes

I'm a total beginner in JavaScript..
Can someone explain me why this will not work? And how to make it work?

function getResults(keywords) {

        foo.foo = function() {
               var bar = foo.getSomeText; // Contain "blabla"
        };

        return bar;

    }

    // Globale scope


    alert(bar); // Do nothing

Edit (sorry for the lack of information):

That's because I want to return some text from an xhr request, and I have to use a function to use the onreadystatechange event .. Here is the original code :

function getResults(keywords) {
     // Effectue une requête et récupère les résultats

    var xhr = new XMLHttpRequest();
    xhr.open('GET', './autoc.php?s='+ encodeURIComponent(keywords));

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
           var response = xhr.responseText;
          var test = response.split('|');

        }



    };


    xhr.send(null);

    return test;

}



var hum = getResults('test');
console.log(hum);

Upvotes: 0

Views: 113

Answers (4)

Sushanth --
Sushanth --

Reputation: 55750

This should work

var bar;
var foo = {getSomeText : 'blabla'};

function getResults(keywords) {

    foo.foo = (function() {
        return bar = foo.getSomeText; // Contain "blabla"
    })();

    return bar;

}

// Globale scope
bar = getResults('hi');

alert(bar); // Do nothing​​​​​​​​​​​​​​​​​​

Fiddle

  • Your initial code will not work because of syntax error as bar is not defined.
  • foo is an object here and even that is not defined. So you need to create the object.
  • getResults returns bar which can be redefined inside the function if you explicitly execute the function and need to assign it to a variable bar in the global scope.

UPDATE

AJAX is asynchronous and you are trying to return the value from the function , which is being set in the callback function. Because the request is asynchronous the function is already returned by the time it hits the callback function. So test will always be undefined in the second case

Upvotes: 1

Vinod Vishwanath
Vinod Vishwanath

Reputation: 5911

The scope of any variable simply depends on where it is declared. If you declare it directly in the script tag, instead of in a method within the script tag block, it will be a global variable.

It's not clear what you're trying to do in your code sample though, because, in "foo.foo", the first "foo" is an undefined entity. You can try this:

<script type="text/javascript">
var foo = {}// creating empty global object named 'foo'

foo.foo = function()//defining method foo() on object foo
{
    var bar = "some random text";

//// more coding here

return bar;

}

var myBar = foo.foo();// get text from method. Note that the method call should be post method definition
alert(myBar);
</script>

Javascript is easy and fun. I'd suggest reading some introductory texts and seeing code samples to understand it.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382454

The scope of a variable in javascript is simple. It's either :

  • the function where it is declared
  • the global scope (window in a browser) if it's not declared in a function

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71939

foo.foo = function() {
    var bar = foo.getSomeText; // Contain "blabla"
};
return bar;

Ignoring the fact that foo does not seem to have been declared, bar is declared inside of a function, so it only exists there, as JavaScript has function scope. You cannot access it outside that function scope, so you cannot return it as you're trying to do here.

You could only return bar if it was declared outside that function:

var bar = foo.getSomeText; // Contain "blabla"
foo.foo = function() {

};
return bar;

Upvotes: 1

Related Questions