V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Exceptionluo
V2EX  ›  JavaScript

对执行结果无法理解 ,求助~

  •  
  •   Exceptionluo · 2018-04-24 23:01:11 +08:00 · 3057 次点击
    这是一个创建于 2164 天前的主题,其中的信息可能已经有所发展或是发生改变。
    var My = {}
    My.namespace = function (name) {
    
        var parts = name.split(',')
    
    
        var current = My;
    
        for (i in parts) {
            if (!current[parts[i]]) {
                current[parts[i]] = {}
                console.log(current, My, i, current === My)
            }
            current = current[parts[i]]
        }
        
    
    }
    
    My.namespace('dom,style')
    console.log(My)
    
    
    代码如上,对最终的执行结果无法理解
    为何 style:{}会挂载到 My 上面呢
    每次 current[parts[i]] = {}  执行后
    再执行 current = current[parts[i]]  
    current 被设置成{} 他又是如何与 My 保持关联的呢
    
    
    5 条回复    2018-04-24 23:26:25 +08:00
    chenstack
        1
    chenstack  
       2018-04-24 23:08:46 +08:00
    不太理解所说的 style:{}挂载到 My 上面,第一次循环相当于 My.dom = {}; current = My.dom; 第二次循环相当于 My.dom.style = {};
    Exceptionluo
        2
    Exceptionluo  
    OP
       2018-04-24 23:21:26 +08:00
    @chenstack 为什么第二次循环相当于 My.dom.style = {};呢 就是这里不理解
    rabbbit
        3
    rabbbit  
       2018-04-24 23:21:50 +08:00
    第一次循环结束后
    current 指向 My["dom"],值是 {}
    nanyang24
        4
    nanyang24  
       2018-04-24 23:25:49 +08:00
    @Exceptionluo 第一次循环之后 `current = My.dom`。第二次循环:`current[parts[1]] = {}` 相当于 `My.dom.style = {}`
    Exceptionluo
        5
    Exceptionluo  
    OP
       2018-04-24 23:26:25 +08:00
    @rabbbit @chenstack 瞬间就懂啦 感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3247 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:46 · PVG 19:46 · LAX 04:46 · JFK 07:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.