简体   繁体   English

XMLHttpRequest JavaScript原型不起作用

[英]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. 我们正在尝试通过在另一个网站上添加w3-include-html函数,然后在* .js文件中添加一些xmlhttprequests来包含我们的网站。

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. 这似乎可行,只有从另一个.js文件中调用函数才能停止执行。 Manually calling the function from browser-console throws 从浏览器控制台抛出异常手动调用该函数
Uncaught ReferenceError: splash is not defined at :1:1 未捕获的ReferenceError:飞溅未定义为:1:1
This only happens for functions that are also prototypes. 这仅适用于也是原型的函数。

First .js file: 第一个.js文件:

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: 第二个.js文件:

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;
[...]

eval works in local scope, so your eval在本地范围内有效,因此您的

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: 如果要在全局范围内评估代码,则可以使用“间接eval ”技巧:

(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. 使用XHR请求脚本代码,然后eval似乎已结束。 You could just append a script element to the page instead. 您可以只向页面添加script元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM