2016-01-22 66 views
0

我一直在阅读关于命名空间,对象文字,IIFE等,我试图理解以下哪个是命名空间JavaScript代码的正确方法?如何使用或不使用IIFE命名空间JavaScript代码?

使用IIFE

let myApp = myApp || {}; 

myApp.some_var = "someString"; 

myApp.some_func = (function(){ const some_const = 1; 

let some_other_func = function(){ 
    console.log(some_const); 
}; 

return { 
    some_other_func: some_other_func 
} 

}()); 

myApp.another_func = (function(){ const another_const = 2; 

let another_func = function(){ 
    myApp.some_func.some_other_func(); 
}; 

return { 
    another_func: another_func 
} 

}()); 

命名空间具有嵌套外部函数不使用IIFE

let myApp = myApp || {}; 

myApp.some_var = "someString"; 

myApp.some_func = function(){ const some_const = 1; 

let some_other_func = function(){ 
    console.log(some_const); 
}; 

return { 
    some_other_func: some_other_func 
} 

}; 

myApp.another_func = function(){ const another_const = 2; 

let another_func = function(){ 
    myApp.some_func.some_other_func(); 
}; 

return { 
    another_func: another_func 
} 

}; 

命名空间与内部嵌套函数具有嵌套外部函数命名空间

let myApp = (function() { let some_var = "someString"; 

let some_func = function(){ 
    const some_const = 1; 

    let some_other_func = function(){ 
     console.log(some_const); 
    }; 

    return { 
     some_other_func: some_other_func 
    } 
}; 

let another_func = function(){ 
    const another_const = 2; 

    let another_func = function(){ 
     some_func.some_other_func(); 
    }; 

    return { 
     another_func: another_func 
    } 
}; 

return { 
    some_var: some_var, 
    some_func: some_func, 
    another_func: another_func 
} 

}()); 

IIFE功能

let a_func = (function(){ let some_var = "someString"; }()); 

let some_func = (function(){ const some_const = 1; 

let some_other_func = function(){ 
    console.log(some_const); 
}; 

return { 
    some_other_func: some_other_func 
} 

}(another_func, a_func)); 

let another_func = (function(){ const another_const = 2; 

let another_func = function(){ 
    some_func.some_other_func(); 
}; 

return { 
    another_func: another_func 
} 

}(a_func, some_func)); 

编辑:在我自己的特殊例子的代码将在node.js中运行,并且“应用”将是代码少于500行,所以我打算把它全部放在一个文件中。我特别感兴趣的答案不建议使用AMD,CommonJS,Browserify,Webpack,ES6模块等。

回答

0

恕我直言,最好的方法是使用CommonJS标准,从你的代码我可以看出你已经是使用EcmaScript6,所以最好的方法是使用ES6 modules

在我自己的项目中,我使用browserify - 它允许我使用的NodeJS/CommonJS的模块:由您提出

// module1.js 
exports.foo = function(value) { 
    return value + x; 
}; 

exports.CONST = 1; 

// module2.js 
var m1 = require('module1'); 
m1.foo(); 

所有的方法,大致相当,我个人喜欢revealing-module-pattern,并尝试使用它时,我不能使用CommonJS。我也喜欢在模块开始移动return语句,它有助于可读性:

var MyModule = (function() { 
    'use strict'; 

    return { 
    foo: foo 
    }; 

    function foo() { 
    return 1; 
    } 
}()); 

另一个重要的问题是有封闭在IFFE整个模块的代码,尤其是当你使用strict mode和您连接js文件。

OK,这可能不是回答你的问题,但也许它帮助你看到更大的画面...