[TIL] Common JS

ytwicey·2020년 11월 17일
0

TIL

목록 보기
15/23
post-thumbnail

Cominciamo

드디어 알게 되었다. 벨로그에서 코드 작성하는 방법을...
이제서야 알다니. 나의 캡쳐창을 이제 날릴 수 있게 되었다. 그리고 엄청난 vsc 익스텐션도 알게 되었다. tabnine... 코드를 다 써준다. 내가 할 것은 엔터치기 밖에 없음.

아니, Common JS가 넘 어려워서 강의를 세번이나 돌려봤는데도 어렵다. 소크라티브 다 틀렸어... 제 2의 클로저 같은 느낌적인 느낌... 그래도 할 수 있다. 할 쑤 이써!!!


1. Common JS

CommonJS(http://www.commonjs.org/) 는 JavaScript를 브라우저에서뿐만 아니라, 서버사이드 애플리케이션이나 데스크톱 애플리케이션에서도 사용하려고 조직한 자발적 워킹 그룹이다. CommonJS의 'Common'은 JavaScript를 브라우저에서만 사용하는 언어가 아닌 일반적인 범용 언어로 사용할 수 있도록 하겠다는 의지를 나타내고 있는 것이라고 이해할 수 있다.
출처 여기 >> JavaScript 표준을 위한 움직임: CommonJS와 AMD

기본적으로 자바스크립트의 서버사이드를 어떻게 범용적으로 모든 사람들이 잘 쓸 수 있을 것인가에 대한 논의에서 나온 방법이 모듈화고, 크게 두 그룹에서 지정한 방법으로 모듈화를 쓰고 있음. 그 중에서 우리는 Common JS의 방식을 따르고 있다.

모듈은 총 3가지의 특징을 가지고 있다.
- scope를 가진다.
- 모듈 정의는 exports 객체를 사용한다.
- 모듈 사용은 require 함수를 사용한다.

그러니까 말하자면, 아래와 같은 형태라고 생각하면 된다. exports 객체는 이렇다고 생각하면 된다.

const module = { 
	exports : {}
}

const exports = module.exports

2. SOCRATIVE

이것을 기반으로 어떻게 사용하는지 예제를 통해서 보자.

1.

Assume you have the following in subject.js:

let x = 10
let mod = require('./lib/my-module.js') 
let result = mod.x

...and the following in lib/my-module.js:

let x = 20
exports.x = 30

After subject.js uns, what will be the value of result?

여기서 mod는 my-module.js의 값을 참조함. 그런데, my-module 파일에서 exports를 한 값은 30이고, 따라서 result인 mod.x = 30임.


2.

Assume you have the following in subject.js:

let mod = require('./lib/my-module.js')
let result = mod.x

...and the following in lib/my-module.js:

let x = 10
exports.x = 20 
module.exports.x = 30

After subject.js runs, what will be the value of result?

여기서 다시 mod는 my-module파일을 참조한다. 그리고 my-module 파일에서 exports는 module.exports를 숏컷이라고(강의자료에서 그렇게 이야기 함) 생각하면 된다. 따라서 exports.x === module.exports.x 와 같고, 20이던 것을 30으로 재할당하였기 때문에 result인 mod.x 는 30


3.

Assume you have the following in subject.js:

let mod1 = require('./lib/my-module.js');
let mod2 = require('./lib/my-module.js'); 
let result = (mod1 === mod2);

...and the following in lib/my-module.js:

exports.obj = { name: "Alice" };

After subject.js runs, what will be the value of result?

mod1, mod2가 둘다 마찬가지로 my-module 파일을 참조하고, exports가 되는 값은 객체임. 객체는 레퍼런스 타입이기 때문에 같은 주소를 참조하면 같은 값임.
여기서 mod1, mod2는 { name: "Alice" }라는 같은 주소값을 참조하고 있기 때문에 mod1 === mod2는 참이다.


4.

Assume you have the following in subject.js:

var mod1 = require('./lib/my-module.js');
var mod2 = require('./lib/my-module.js');

mod1.increment();
var result = mod2.increment();

...and the following in lib/my-module.js:

var counter = 0;
exports.increment = function () {
  counter += 1;
  return counter;
};

After subject.js runs, what will be the value of result?

답은 2. 왜냐하면 이미 mod1.increment()로 counter는 1인 상태고,
mod2.increment()하면 값은 2가 된다. mod1, mod2가 전부 같은 my-module 값을 참조 하고 있기 때문에 counter가 2번 ++된다.

5.

Assume you have the following in subject.js:

let mod1 = require('./lib/my-module.js');
let mod2 = require('./lib/my-module.js');

...and the following in lib/my-module.js:

console.log("Loading module!")

After subject.js runs, how many logs in the console will you see?

mod1, mod2가 같은 값을 참조 하고 있기 때문에, 이미 mod1에서 파일을 실행했다는 데이터가 저장이 되어, 1번만 콘솔에 찍히게 된다.

profile
always 2B#

0개의 댓글