Search code examples
javascriptxmlhttprequestprototype

XMLHttpRequest javascript prototypes not working


We're trying to include our website by w3-include-html function on another website, followed by some xmlhttprequests for the *.js files.

function loadJS(url,onDone,onError){
var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
        if(xhr.status==200||xhr.status==0){
            setTimeout(function(){
                try{
                    eval(xhr.responseText);
                }catch(e){
                }
                onDone();
            }.bind(this),1);
        }else{
        }
    }
}.bind(this);
try{
    xhr.open("GET",url,true);
    xhr.send();
}catch(e){
}};

This seems to work, only calling on function from another .js-file stops the execution. Manually calling the function from browser-console throws
Uncaught ReferenceError: splash is not defined at :1:1
This only happens for functions that are also prototypes.

First .js file:

var eless = function () {
this.$body = $('body');
var self = this;
window.dataLayer = window.dataLayer || [];

this.init();
this.loop();
console.log("before");
new splash();
console.log("after");

second .js file:

var splash = function() {
console.log('after after');
console.log(this.init);
this.init();
console.log("after after after");
};
splash.prototype = {
init: function () {
    var self = this;
[...]

Solution

  • eval works in local scope, so your

    eval(xhr.responseText);
    

    ...runs the code as though it were inside that callback. Top-level function declarations and such won't be globals.

    If you want to evaluate the code at global scope, you can use the "indirect eval" trick:

    (0, eval)(xhr.responseText);
    

    But, I would strongly recommend stepping back and re-evaluating what you're doing. Using XHR to request script code you then eval seems off. You could just append a script element to the page instead.