Say I have a file ‘test.js’ with the following contents:
var test = 'something';
Then I have a primary script that needs to load up test.js to grab the test variable.
Obviously this works:
$.ajax({dataType: "script", cache: true, url: 'test.js'});
The issue is that the variable test exists in the global scope. I’m curious if there’s a way to add it into an object and keep it out of the global scope.
Something like:
function scriptloader() {
this.grabscript = function() {
return $.ajax({dataType: "script", cache: true, url: 'test.js'});
}
}
var myloader = new scriptloader();
myloader.grabscript();
Where ideally myloader would contain the loaded variable test. However, I can console.log(test) and still see ‘something’.
Is there a way to lock the loaded script into scope or am I dreaming?
You could try something like this:
The
scriptloaderinstance would then get a property calledtest.