范围和命名空间问题 [英] Scope and Namespace questions

查看:81
本文介绍了范围和命名空间问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于学习目的,我正在检查各种JavaScript库.基本上,我想找到初始化命名空间的最佳方法,并了解专家如何在其库中加载所有相关文件.我在主文件(例如,将其命名为myNameSpace.js)中遇到了几次,库用户会在几个文件中调用它:

I was examining various JavaScript libraries for learning purposes. Basically I want to find the best way to initiliaze a namespace and see how pros load up all the associated files in their libraries. I came across this a few times in the main file (for example lets call it myNameSpace.js) that the library user would call in a few libraries:

(function() {

    var jsFiles = window.MyNameSpace;

    window.MyNameSpace = {
        _getScriptLocation: (function() { 
            /* some code here */ 
        })
    };

    if(!jsFiles) { 
        jsFiles = [/* An array of ALL the library files! */];
    }

    for(var i=0, len = jsFiles.length; i<len; i++) { 
        scriptTags[i] = "<script src='" + jsFiles[i]  + "'></script>"; 
    }

    if(scriptTags.length > 0) { 
        document.write(scriptTags.join("")); 
    }

})();

因此,通过这种设置,如果库用户只想包括库的某些部分,则他们将在加载myNameSpace.js之前通过执行以下操作来指定:

So, with this setup, if the library user wanted to include only certain portions of the library, they would specify before loading the myNameSpace.js by doing something along the lines of:

<script type='text/javascript'> window.MyNameSpace = ["libraryFile1.js", "libraryFile2.js", "libraryFile3.js"]</script>
<script type='text/javascript' src="MyNameSpace.js"></script>

我的问题是,window.MyNameSpace是一个对象,如果脚本将jsFiles作为window.MyNameSpace分配给数组设置,这将是通过引用进行的分配,对吗?但是紧接在那一行之后,window.MyNameSpace被完全改变了.那么jsFiles不应该不再引用传入的原始数组吗?在我的理解中,我在这里想念的是什么?

My question is, window.MyNameSpace is an object and if the script assigns jsFiles to an array setup as window.MyNameSpace, this is going to be an assignment by reference, correct? But immediately after that line, window.MyNameSpace gets completely changed. So shouldn't jsFiles no longer reference the original array that was passed in? What am I missing here in my understanding?

推荐答案

JS不分配按引用",而是复制,但是当分配对象时,我们复制其地址,而不是对象自己".

JS does not assign "by reference", assignment is copying, but when we assign objects, we copy their addresses, not objects "themselves".

window.MyNameSpace = ["libraryFile1.js", "libraryFile2.js", "libraryFile3.js"]

window.MyNameSpace指向内存中的某个对象.假设其地址为0x12345

window.MyNameSpace point to some object in memory. Let's assume its address is 0x12345

var jsFiles = window.MyNameSpace;

jsFiles现在指向同一对象(0x12345)

jsFiles now points to the same object (0x12345)

window.MyNameSpace = {...}

window.MyNameSpace现在指向其他对象(将其设置为0x56789),但jsFiles仍指向第一个对象(0x12345).

window.MyNameSpace now points to some other object (let it be 0x56789), but jsFiles still points to the first object (0x12345).

这篇关于范围和命名空间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆