简体   繁体   English

如何在另一个.js文件中访问全局JS对象

[英]How to acces a global JS-Object in another .js-File

How do i acces an object which was initialized in my HTML-Document? 如何访问在HTML文档中初始化的对象?

My HTML-Document looks like this: 我的HTML文档如下所示:

    ...

<script type="text/javascript" id="controller">var controller = false;</script>

    ...

<body onload="controller = new CTRLclass()">

    ....

How do I call controller.doAMethod() in an external Javascript-File using DOM-Operations or simmilar? 如何使用DOM-Operations或simmilar在外部Javascript-File中调用controller.doAMethod()?

edit: PPL, i have many .js-Files and my controller is creating an instance of another class in his constructor. 编辑:PPL,我有很多.js文件,我的控制器正在他的构造函数中创建另一个类的实例。 In the created instance of the class i need acces to the controller to call an update-Function. 在创建的类实例中,我需要访问控制器以调用update-Function。 Like: controller -> creates instance of class. 像:控制器->创建类的实例。 class -> needs to call controller.update(). 类->需要调用controller.update()。 How do i acces controller in 'class' - Thats all 我如何在“班级”访问控制器-就是所有

THX! 谢谢!

You don't need the onload tag to initiate onload tasks. 您不需要onload标记来启动onload任务。 Just put this is the external javascript file: 只需将其放在外部javascript文件中即可:

var controller = false;
function Init(){
    controller = new CTLRclass;
}
function addEvent(el, eType, fn, uC) {
    var uC = uC || true;
    if (el.addEventListener) {
        el.addEventListener(eType, fn, uC);
        return true;
    } else if (el.attachEvent) {
        return el.attachEvent('on' + eType, fn);
    } else {
        el['on' + eType] = fn;
    }
}
addEvent(window, 'load', Init);

I actually can't envisage why you would want to do the above. 实际上,我无法想象您为什么要执行上述操作。 Simply strip out all of the Javascript in the above, so all you have is: 只需剥离上面的所有Javascript,那么您所拥有的就是:

... ...

<script type="text/javascript" src="myjsfile.js"></script>

...

<body>

....

And in myjsfile.js do somthing like 在myjsfile.js中做类似

window.onload = function(){
    var controller = new CTRLclass();
}

If it must be global, then you can move it outside of the onload function: 如果必须是全局的,则可以将其移到onload函数之外:

var controller = false
window.onload = function(){
    controller = new CTRLclass();
}

Use of jQuery would make it more elegant, of course, as you wouldn't risk overriding any existing onloads: 当然,使用jQuery会使它更加优雅,因为您不必冒险覆盖任何现有的onload:

var controller = false
$(document).ready(function(){
    controller = new CTRLclass();
});

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

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