Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Introduction to the JavaScript shell

들어가며

이 문서는 모질라 CVS 서버에서 자바스크립트 셸을 가져와 빌드하는 방법을 소개하고 있습니다. 또한 시험삼아 개발 버전을 빌드하는 방법에도 관심을 기울이고 있습니다.

게다가 이 문서는 쉘에서 자바스크립트 코드를 테스트하고 자바스크립트로 작성한 프로그램을 실행하는 방법에 대한 간단한 소개도 포함하고 있습니다.

자바스크립트 셸 설치하기

CVS 서버에 접속합시다

CVS에서 다른 모질라와 관련된 프로젝트의 산물을 얻는 것과 마찬가지로 자바스크립트 셸을 사용하려면 먼저 CVS 서버에 로그인해야 합니다. cd 명령을 사용하여 코드를 체크아웃할 기본 디렉토리로 들어가, 다음과 같은 명령어를 명령행에 입력합니다.

cvs -d :pserver:[email protected]:/cvsroot login

프롬프트가 뜨면 패스워드를 입력합니다. anonymous 라고 입력하면 됩니다.

자바스크립트 셸 트렁크 버전 설치하기

한번 CVS 서버에 로그인하였으면 필요한 파일을 받아와야 합니다. 트렁크란 CVS에서 중심이 되는 개발 흐름을 말합니다. 트렁크 버전을 다운로드 하기 위해 CVS 트리의 루트로 지정한 디렉토리로 들어가 다음과 같이 명령을 입력합니다.

cvs -d :pserver:[email protected]:/cvsroot co -l mozilla/js/src mozilla/js/src/config mozilla/js/src/editline mozilla/js/src/fdlibm

자바스크립트 셸을 설치하는 데 필요한 모든 파일을 체크아웃하였습니다. 이제 다음과 같은 명령 두개만 입력하면 바로 설치할 수 있습니다:

cd mozilla/js/src
make -f Makefile.ref

컴파일이 끝나면 우리가 설치한 디렉토리에 실행할 수 있는 파일인 js가 들어 있어야 합니다. 예를 들어 Mac OS X에서라면, 실행 파일은 Darwin_DBG.OBJ/js의 경로에 놓일 것입니다.

이 상태에서 바로 자바스크립트 셸 사용하기를 실습해 볼 수도 있습니다.

자바스크립트 셸 브랜치 버전 설치하기

간단히 설명하면 브랜치란 중심이 되는 개발 흐름에서 곁가지를 쳐 나온, 작은 부분에 대한 개발 흐름을 뜻합니다. 자바스크립트 셸의 실험적이고 독특한 브랜치 버전을 사용하기를 원한다면 파일을 체크아웃 할 때 -r branchname 을 추가하는 것만으로도 바로 사용할 수 있습니다.

설치 과정은 트렁크 버전과 같으나, 체크아웃을 할 때 cvs co... 행의 내용이 조금 바뀝니다.

cvs -d :pserver:[email protected]:/cvsroot co -l -rbranch_name mozilla/js/src mozilla/js/src/config mozilla/js/src/editline mozilla/js/src/fdlibm

branch_name을 체크아웃하기 원하는 브랜치 버전의 이름으로 변경하세요. 예를 들어 JavaScript 1.7 의 알파 브랜치인, JS_1_7_ALPHA_BRANCH로 변경할 수 있습니다.

컴파일하는 방법은 앞서 설명한 방법과 같습니다.

자바스크립트 셸 사용하기

자바스크립트 셸은 두가지 모드로 운영할 수 있습니다. 먼저 여러분은 여러분이 새로운 자바스크립트 코드를 테스트하기 위해 프롬프트에 직접 입력하고 결과를 바로 얻는, 인터랙티브 셸로 사용할 수도 있습니다. 혹은 자바스크립트 프로그램 파일을 명령행에 입력하여 실행할 수도 있습니다.

노트: 자바스크립트 셸은 자바스크립트 엔진을 위한 테스트 환경입니다. 그러므로 사용 가능한 함수나 옵션은 변경될 수 있습니다.

명령행 옵션

셸을 설정하고 사용하는 데 필요한 명령들입니다. 간단히 요약하면 다음과 같습니다.

  • -bbranchlimit
    • 최대 브랜치 개수를 정합니다.
  • -cstackchunksize
    • 스택 덩어리의 크기를 정합니다.
  • -C
    • 프로그램을 컴파일만 하고 실행은 하지 않습니다. 굳이 실행하지 않고도 문법 에러를 빠르게 확인할 때 사용할 수 있습니다.
  • -escript
    • 해당script 를 실행합니다. 해당 스크립트 안에는 실행할 수 있는 코드가 들어 있어야 합니다.
  • -ffilename
    • filename에 해당하는 자바스크립트 프로그램을 실행합니다.
  • -i
    • 인터랙티브 모드를 활성화합니다.
  • -P
    • 이 문서의 저자도 아직 확실히 무슨 옵션인지 모르겠다는군요. :-)
  • -s
    • 정적 경고모드를 활성화합니다.
  • -Sstacksize
    • 최대 스택 크기를 정합니다.
  • -v
    • 경고 정보를 봅니다.
  • -w
    • 경고 메시지 보기를 활성화합니다.
  • -W
    • 경고 메시지 보기를 불활성화합니다.
  • -x
    • E4X XML 모드를 활성화합니다.

셸 실행하기

인터랙티브 모드로 셸을 실행하고 싶다면 다음과 같이 입력합니다.:

js

foo.js라는 파일을 불러 실행하고 싶다면 다음과 같이 입력합니다.:

js -f foo.js

foo.js를 실행하고 나서 인터랙티브 셸로 전환하고 싶다면 다음과 같이 할 수 있습니다:

js -f foo.js -f -

인터랙티브 모드에서 셸 사용하기

인터랙티브 모드에서 당신은 손으로 직접 오브젝트와 함수들을 입력하여 자바스크립트를 실행하고 구문들을 테스트해 볼 수 있습니다. 이것은 우리의 아이디어를 시험해보기 편리한 방법이며, 자바스크립트 엔진을 사용하는 개발자들이 이 언어의 새로운 요소들을 시험해보는 중요한 장이기도 합니다.

빌트-인 함수

자바스크립트 셸을 더욱 유용하게 사용하기 위하여, 당신이 자바스크립트 프로그램이나 인터랙티브 모드에서 사용할 수 있는 함수들이 준비되어 있습니다.

build()

자바스크립트 셸이 빌드된 시간과 날짜를 반환합니다.

clear([object] )

object의 속성들을 비웁니다. 다른 옵션 없이 clear()라고만 실행하면 모든 속성이 초기화됩니다.

Note: 다른 옵션 없이 clear() 를 실행하면 정말로 모든 것이 지워집니다. 지금 설명하는 빌트-인 함수들도 포함해서 말이지요.

clone(function, [scope] )

해당 function의 오브젝트들을 복제합니다. scope가 따로 정해지지 않았다면 새로운 오브젝트의 부모 요소는 기존의 것과 완전히 동일해집니다. 기존 함수에서 일부만을 떼어 복사하고 싶다면 scope로 범위를 지정해 주세요.

dis([function] )

다른 프로그램에 사용하거나 특별한 함수로 만들기 위해 자바스크립트를 바이트코드로 만드는(디스어셈블 하는) 함수입니다.

예를 들어 다음과 같은 자바스크립트가 있다고 합시다.

function test() {
  var i = 3;
  print(i+2);
}

dis(test);를 실행하면 다음과 같은 결과를 볼 수 있습니다:

main:
00000:  uint16 3
00003:  setvar 0
00006:  pop
00007:  name "print"
00010:  pushobj
00011:  getvar 0
00014:  uint16 2
00017:  add
00018:  call 1
00021:  pop
00022:  stop

Source notes:
  0:     0 [   0] newline 
  1:     3 [   3] var     
  2:     7 [   4] newline 
  3:    18 [  11] xdelta  
  4:    18 [   0] pcbase   offset 11

dissrc([function] )

다른 프로그램에 사용하거나 특별한 함수로 만들기 위해 자바스크립트를 바이트코드로 만들고 소스를 보여주는 함수입니다. 이 함수는 파일에서 로딩된 함수에만 적용할 수 있으며, 셸에서 명령을 입력할 때에도 -f 옵션을 주거나 load() 함수를 사용해야 합니다.

당신의 프로그램에 doStuff() 함수가 포함되어 있다고 가정합시다.

function doStuff(input) {
	print("Enter a number: ");
	var n1 = readline();
	print("Enter another one: ");
	var n2 = readline();
	
	print("You entered " + n1 + " and " + n2 + "\n");
}

그러면 dissrc(doStuff) 함수를 실행한 결과를 보겠습니다.:

;-------------------------  10:         print("Enter a number: ");
00000:  10  name "print"
00003:  10  pushobj
00004:  10  string "Enter a number: "
00007:  10  call 1
00010:  10  pop
;-------------------------  11:         var n1 = readline();
00011:  11  name "readline"
00014:  11  pushobj
00015:  11  call 0
00018:  11  setvar 0
00021:  11  pop
;-------------------------  12:         print("Enter another one: ");
00022:  12  name "print"
00025:  12  pushobj
00026:  12  string "Enter another one: "
00029:  12  call 1
00032:  12  pop
;-------------------------  13:         var n2 = readline();
00033:  13  name "readline"
00036:  13  pushobj
00037:  13  call 0
00040:  13  setvar 1
00043:  13  pop
;-------------------------  14: 
;-------------------------  15:         print("You entered " + n1 + " and " + n2 + "\n");
00044:  15  name "print"
00047:  15  pushobj
00048:  15  string "You entered "
00051:  15  getvar 0
00054:  15  add
00055:  15  string " and "
00058:  15  add
00059:  15  getvar 1
00062:  15  add
00063:  15  string "\\n"
00066:  15  add
00067:  15  call 1
00070:  15  pop
00071:  15  stop

evalcx(string[, object] )

Evaluates the JavaScript code instring . Ifobject is specified, the code is executed in that object, treating it as a sandbox.

Ifstring is empty andobject is not specified, evalcx() returns a new object with eager standard classes.

Ifstring is "lazy" andobject is not specified, evalcx() returns a new object with lazy standard classes.

Note: evalcx() is only useful for people doing deep internal work on the JavaScript engine, for testing evalInSandbox-like environments in the shell.

gc()

가비지 콜렉터를 실행하여 메모리를 깨끗이 비웁니다.

getpda(object )

Returns the property descriptors for the specifiedobject .

getslx(object )

Returns the script line extent, which is the number of lines of code comprising the specified object.

help([command ...] )

Displays brief help information about the specified commands, or about all available functions if none are specified.

intern(string )

Internalizes the specified string into the atom table. Every string has a unique identifier, called an atom. This system makes it easier to do comparisons between strings.

Note: This function is intended only for use when testing the JavaScript engine.

line2pc([function, ] line )

Returns the program counter value corresponding to the specifiedline of code. Iffunction is specified,line is an offset into the specified function.

load(filename1[filename] )

Loads the files with the specified names.

notes([function] )

Shows the source notes for the specified function. Source notes contain information that map the bytecode to the source code, which is used when decompiling the code, such as when using the dissrc() function.

options([option ...] )

Lets you set or get options. If you specified options on the command line, the results of calling options will indicate which options you requested. You can also pass in new options to set.

If you start the shell with the command js -x, then the options() function will return xml. If you start the shell with no options, and decide you want to enable XML mode, you can do so by issuing the command:

options('xml');

The available options are:

Option Name Description
strict Strict 모드를 활성화합니다.
werror 경고를 에러로 속여 출력합니다.
atline When atline is enabled, comments of the form //@linenum set the number of the following line to num .
xml XML 모드를 활성화합니다.

pc2line(function, [pc] )

Returns the line number of the JavaScript code that corresponds to the first line of the specifiedfunction . If you specify a program counter offset into the function, the line number of the line of code containing that offset is returned.

print([expression ...] )

문자열이면 문자열, 식이면 식으로expression 의 값을 구하여 그 결과를 stdout 으로 출력합니다.

quit()

셸에서 빠져나옵니다.

readline()

표준 입력으로 읽어들여 호출자에게 되돌려줍니다. 이 함수를 사용하여 자바스크립트에서 인터랙티브 셸 프로그램을 만들 수 있습니다.

seal(object[, deep] )

Seals the specifiedobject , or an object graph ifdeep is true. By sealing an object or object graph, you disable modification of those objects.

stats([string ...] )

Dumps statistics. Valid options arearena ,atom , andglobal .

Option Description
arena Outputs the arena table.
atom Outputs the atom table.
global Outputs the global name table.

Anarena is a large block of memory from which the JavaScript engine allocates sub-blocks in order to optimize performance; issuing a large number of malloc() calls for each individual block is inefficient, so the engine creates arenas, then uses an internal memory management system to allocate memory from within those. The arena table is a list of all the arenas that have been allocated by the shell. stats("arena") lets you inspect the arena table so that you can see how a test case uses arenas.

Anatom is a unique identifier for a string. In order to optimize comparisons between strings, each string is given an atom. These atoms are stored in a hash table, which you can display using the command stats("atom").

stats("global") displays the global name table, which contains the names and information about each object in memory.

stringsAreUtf8()

문자열이 UTF8 형식으로 인코드 되어있을 경우 true를, 그 외의 경우 false를 반환합니다.

testUtf8(mode )

UTF-8이 제대로 동작하는지 1에서 4까지의 정수 변수를 입력하여 테스트합니다. 이것은 UTF-8 문자열이 제대로 처리되는지 확인하는 간단한 디버깅 명령으로, 일반적으로는 이 명령을 사용하여 따로 확인하기보다는 자바스크립트 엔진에서 직접 작업하며 확인하는 것이 빠릅니다.

throwError()

JS_ReportError() 함수에서 에러를 받아 지정된 방식으로 처리합니다.

Note: 이 함수는 자바스크립트 엔진을 시험하는 목적으로만 사용하세요.

tracing([toggle] )

true 혹은 false로 지정하여 트레이스 모드를 켜거나 끌 때 사용합니다. 따로 설정한 것이 없다면 tracing() 함수는 일반적인 설정사항을 반환할 것입니다.

Tip: 이 함수는 자바스크립트를 JS_THREADED_INTERP로 빌드했을 때만 사용할 수 있습니다. 이 옵션은 jsinterp.c에서 지정할 수 있습니다.

trap([function, [pc,]] expression )

자바스크립트 코드의 지정된 위치에 트랩을 설정합니다. 해당functionpc 오프셋에expression 에 해당하는 바이트 코드를 집어넣을 수 있습니다.

line2pc()와 함께 사용하면 강력한 디버깅 방법이 됩니다 예를 들어 원래는 doSomething()을 사용하는 함수의 6번째 줄을 실행할 때 메시지를 출력하고 싶다면 다음과 같이 사용할 수 있습니다.

trap(doSomething, line2pc(test, 6), "print('line 6!\n')");
Note: 트랩이 설정된 동안 프로그램 내의 해당 바이트 코드는 untrap()을 사용하여 트랩을 해제할 때 까지 trap 바이트 코드로 대체됩니다.

untrap(function [, pc] )

지정된functionpc 오프셋에서 트랩을 삭제합니다.pc 가 지정되지 않았다면 해당 함수수에 접근할 때 걸리는 트랩을 삭제하게 됩니다. 이 함수는 트랩이 지정되지 않았을 경우에는 아무 동작도 하지 않습니다.

version([number] )

version() 함수는 자바스크립트 버전을 반환합니다. 그다지 쓸 일이 있는 함수는 아니지요.

문서 태그 및 공헌자

 최종 변경: jigs12,