Node.js or Javascript Global Scope Test
NodeJS 2012. 11. 20. 15:34
1. Client-Side Javascript 전역 객체
// 명시적 전역 변수 선언
var global1 = 'global1';
(function(){
// 암묵적 변수 선언(안티패턴)
global2 = 'global2';
this.global3 = 'global3';
})();
console.log(typeof window.window.global1); // string
console.log(typeof window.window.global2); // string
console.log(typeof window.window.global3); // string
// delete 연산자로 window 객체의 property 삭제
delete window.window.global1;
delete window.window.global2;
delete window.window.global3;
console.log('');
// 명시적으로 선언된 global1 전역 변수는 엄밀히 말해 아래 결과와 같이 delete 연산자로 객체가 소멸되지 않는다.
// 즉, 객체 속성 및 배열의 요소를 제거하는 delete 연산자로 삭제가 되지 않기 때문에 엄밀히 말해 window 객체의 속성으로 볼 수 없다.
console.log(typeof window.window.global1); // string
console.log(typeof window.window.global2); // undefined
console.log(typeof window.window.global3); // undefined
자바스크립트 변수
자바스크립트 함수 유효범위(Scope)란?
2. Server Side Javascript Node.js 전역 객체
2.1 확장 모듈 helloworldExFn.js 코드
module.exports.helloworldExFn = (function(){
var helloworldEx = function(){
this.id = 'mohwa';
this.name = 'mohwaName';
return this;
}
// 전역 속성 선언 및 할당
global.g_createValue1 = 'g_createValue1';
this['g_createValue2'] = 'g_createValue2';
return helloworldEx;
})();
2.2 호출 페이지 코드
// Node 전역 객체의 Console.log 함수 반환
console.log('1. ' + global.console.log);
// Node 전역 객체의 생성자 함수 반환
console.log('2. ' + global.constructor);
// 빈 전역 객체 반환
console.log('3. ' + this);
// Node.js에서는 Client-Side JS와 달리 함수 밖 "this"는 전역 객체인 global을 가리키지 않는다.
// 빈 전역 객체 생성자 함수 반환
console.log('4. ' + this.constructor);
(function(){
// Node 전역 객체의 Console.log 함수 반환(Client-Side JS와 같이 함수 객체 내부에서는 빈 전역 객체가 아닌 Node 전역 객체 "global"을 반환한다.)
console.log('5. ' + this.console.log);
})();
// 확장 모듈 내부에 전역 변수 생성.
// require(객체) 메서드는 외부 리소스로 제공된 확장 모듈을 가져와 반환({} 타입)한다.
// 그리고 제공된 확장 모듈안 helloworldExFn 맴버는 반환되는 객체의 맴버로 정의된다.
var obj = new require('./helloworldEx.js').helloworldExFn();
// new helloworldExFn() 객체의 id 속성 반환
console.log('6. ' + obj.id);
// new helloworldExFn() 객체의 name 속성 반환
console.log('7. ' + obj.name);
var g_createValue1 = 'g_createValue1';
// 명시적 전역 변수는 g_createValue1를 제거한다.
// 하지만 Client-Side JS와 동일하게 명시적 전역변수는 delete 연산자를 통해 제거되지 않는다.
delete g_createValue1;
// 확장 모듈 내부에서 선언된 암묵적 전역 변수인 g_createValue2를 제거한다.
delete g_createValue2;
// 확장 모듈 내부에서 선언된 암묵적 전역 변수인 g_createValue3를 제거한다.
delete g_createValue3;
console.log('8. ' + typeof g_createValue1);
console.log('9. ' + typeof g_createValue2);
console.log('10. ' + typeof global['g_createValue3']);
3. 결과:
이전 포스트에서 "Node.js 아키텍처 방식"에 대해 간단히 설명한 적이 있다.
즉, "Node 아키텍처 최 상단 레이어"인 "Node Standard LIbrary"를 통해 기존 Client-Side Javascript 문법이 활용 가능하며, 전체 적인 동작 방식(전역객체, 유효범위 등..)또한, 기존 JS와 많은 부분 흡사하다는 것을 알 수 있다.