웹페이지를 동적으로 만들어주는 언어
var를 이용하여 선언한다. 변수의 타입은 지정하지 않는다.
var i = 1;
크게 세 가지로 분류할 수 있다.
문자열과 관련된 속성은 다음과 같은 것들이 있다.
"obg".length // 문자열 길이 (결과 : 3) "obg.".substring(0,2) // 문자열 추출 (결과 : "ob")
confirm("I am ready to play!"); // 대화 상자 출력 var age = prompt("What's your age"); // 입력 상자 출력 if(age < 13) { console.log("You take no responsibility"); // 텍스트 출력 } else { console.log("Play on!"); }
일반적인 변수를 함수의 파라메터로 전달하면 해당 변수의 값이 전달된다.
function myfunction(x) { // x is equal to 4 x = 5; // x is now equal to 5 } var x = 4; alert(x); // x is equal to 4 myfunction(x); alert(x); // x is still equal to 4
객체 또는 배열을 함수의 파라메터로 전달하면 참조가 전달된다.
function myobject() { this.value = 5; } var o = new myobject(); alert(o.value); // o.value = 5 function objectchanger(fnc) { fnc.value = 6; } objectchanger(o); alert(o.value); // o.value is now equal to 6
배열, 객체는 포인터라고 생각하고 다루면 편하다. 배열, 객체를 변수에 대입할 때에도 마찬가지 룰이 적용된다. 다음의 예를 살펴보자.
var arr = [0, 1, 2]; var a = arr; a.push(3); console.log(arr);
위 코드의 결과는 다음과 같다.
[ 0, 1, 2, 3 ]
즉, 변수 a는 arr의 레퍼런스라 보면 된다.
자바스크립트는 메소드 오버로딩을 지원하지 않지만 구현은 가능하다. 다음은 jQuery의 개발자로 유명한 John Resig의 소스1)이다.
// addMethod - By John Resig (MIT Licensed) function addMethod(object, name, fn){ var old = object[ name ]; object[ name ] = function(){ if ( fn.length == arguments.length ) return fn.apply( this, arguments ); else if ( typeof old == 'function' ) return old.apply( this, arguments ); }; } function Users(){ addMethod(this, "find", function(){ // Find all users... }); addMethod(this, "find", function(name){ // Find a user by name }); addMethod(this, "find", function(first, last){ // Find a user by first and last name }); } var users = new Users(); users.find(); // Finds all users.find("John"); // Finds users by name users.find("John", "Resig"); // Finds users by first and last name users.find("John", "E", "Resig"); // Does nothing
암호화할 때 Crypto-JS를 사용할 수도 있다. 그 이유는 클라이언트에서 crypto 모듈을 불러올 방법이 마땅히 없기 때문이다. (있을 수도 있음) Crypto-JS를 다운받은 후 다음 함수를 이용하여 crypt, decrypt를 수행할 수 있다.
function crypt(s) { var words = CryptoJS.enc.Utf8.parse(s); var ciphertext = CryptoJS.enc.Base64.stringify(words); return CryptoJS.AES.encrypt(ciphertext, pass).toString(); } function decrypt(s) { var decrypted = CryptoJS.AES.decrypt(s, pass); var plaintext = CryptoJS.enc.Utf8.stringify(decrypted); return CryptoJS.enc.Base64.parse(plaintext).toString(CryptoJS.enc.Utf8); }
그런데 이상하게도 다운받은 js파일을 불러왔는데 제대로 안되더라 -_-; 클라이언트에서는 다운받은 js 파일 대신 다음을 불러와서 사용할 수 있다.
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
Node.js에서는 다음 링크에서 aes.js를 다운받아 사용한다.
위 링크로 들어가면 Crypto-JS를 이용하여 암호화/복호화 후 node.js와 통신하는 방법을 볼 수 있다.
다음 링크에 잘 정리되어 있다.