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);
This should work
Fiddle
defined.
create the object.
getResultsreturns bar which can be redefined inside the function ifyou 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