gpt4 book ai didi

javascript - 理解 javascript 全局命名空间和闭包

转载 作者:IT王子 更新时间:2023-10-29 03:19:15 27 4
gpt4 key购买 nike

我正在努力提高我对 javascript 中全局命名空间的理解,我对一些事情感到好奇:

  1. 是否存在所有对象(因为除基元外的所有事物都是对象)都要回答的“GOD”(即父对象)对象,如果是,那么该对象将是“窗口”吗?

    <
  2. 为什么在全局级别拥有变量/函数是个坏主意?

  3. 如果在全局范围内使用变量/函数真的不是一个好主意,那么闭包是避免这种情况的最佳方式吗?示例:

    function parent(){
    var x = 'some value';//this var would be considered global to all children functions but not in the true global namespace
    function child1(){
    x.someMethod()
    }
    function child2(){
    x*something;
    }
    function child3(){
    x+=something;
    child2()
    child1()
    }
    child3()
    }
    parent()

最佳答案

  1. Is there a god (i.e. a parent) object?

    Yes.从技术上讲,所有这些基元都是其成员的全局对象;碰巧在浏览器中,window 对象全局对象。

    > window.String === String;
    true
  2. Why is it bad idea to have vars/functions on a global level?

    因为如果您要添加大量第 3 方库/脚本,它们都共享同一个全局对象,那么就有可能发生名称冲突。这是所有使用 $ 作为别名(jQuery、Prototype 等)的库的现实生活问题。

  3. If it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this?

    x 不应被视为全局的。它是通过在 parent() 函数内声明子函数而形成的闭包的一部分。您的代码段的问题 部分是 parent() 是全局的;如果一些其他代码重新声明 parent() 会发生什么?这样会更好:

    (function () {

    function parent(){
    var x = 'some value';
    function child1(){
    x.someMethod()
    }
    function child2(){
    x*something;
    }
    function child3(){
    x+=something;
    child2()
    child1()
    }
    child3()
    }
    parent()

    }());

    x 可以在子函数中访问的事实不错;您应该自己编写这些函数,所以您应该知道 x 的存在。请记住,如果您使用 var 在这些子函数中重新声明 x,则不会影响 parent 中的 x ().

关于javascript - 理解 javascript 全局命名空间和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9773964/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com