편집 그냥 내가 당신의 질문에 직접 대답하지 않는다는 것을 깨달았습니다. . 죄송합니다! 그러나이 방법을 사용하면 몇 가지 대체 기술을 이해하는 데 도움이됩니다.
이것은 때때로 속성이나 기능을 한 번 추가하고 나중에 덮어 쓰지 않으려는 경우와 같이 자주 사용하는 기술입니다.
var module = new function(){
var modules = {}; //internal module cache
return function(name, module){
//return all modules
if(!name) return modules;
//return specific module
if(modules[name]) return modules[name];
//return the module and store it
return modules[name] = module;
}
}
그래서 당신과 같이 사용할 수 있습니다 : 보는
//will store this since it doesn't exist
module('test', 'foo'); //Since 'test' doesn't exist on the internal 'modules' variable, it sets this property with the value of 'foo'
module('test'); // Since we aren't passing a 2nd parameter, it returns the value of 'test' on the internal 'modules' variable
module('test', 'bar'); //We are attempting to change the value of 'test' to 'bar', but since 'test' already equals 'foo', it returns 'foo' instead.
module(); // { 'test': 'foo' } //Here we aren't passing any parameters, so it just returns the entire internal 'modules' variable.
중요한 것은 우리가 '새로운 기능을()'를 사용하고 있다는 점이다. 이것은 할당시에 수행됩니다. 왜냐하면 우리는 실제로 '모듈'을 외부 함수가 아니라 내부 함수로 만들기를 원하기 때문입니다. 그러나 내부 'var 모듈'변수에 대한 클로저를 만들려면 외부 함수가 할당에서 실행되어야합니다.
또한 외부 함수를 작성할 수 자체가 너무 실행되는 것을 알 수 :
var module = function(){
var modules = {};
//other stuff
}();
좋아하지만,'myModule.myProject' 이미 방금 작성한 코드는'myProject' 개체를 방지하지 않을 존재하는 경우 창조되는 것에서? – person0
@Proud_to_be_Noob - 네임 스페이스 초기화 시점은 초기화되지 않은 경우 초기화하고 존재하면 그대로 두는 것입니다. 이것이 바로이 코드의 기능입니다. 다른 일을하려고합니까? – jfriend00
YUI 사람들이 네임 스페이스 함수를 사용할 때 YUI 사람들이 무슨 일이 일어나는지 이해하려고합니다. 그 이유는 그들의 문구가 겹쳐 쓰지 않고 빈 복제 객체를 만들 수 있다는 것을 의미하기 때문입니다. 나는 또한 보여지고있는 것을 기본적으로하는 좋은 방법을 찾아 내려고 노력하고있다. (방금 방금 게시 한 내 네임 스페이스 함수 정의가 마음에 듭니다. 감사합니다.). – person0