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
- 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.
getResultsreturns 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
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
- 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.
getResultsreturns 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.
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
- 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.
getResultsreturns 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
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
- 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.
getResultsreturns 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.