JavaScript

조용휘·2023년 1월 22일
0

JavaScript

목록 보기
1/4

JavaScript

브라우저에서 HTML, CSS를 동적으로 제어하기 위해 만들어진 언어

Node.js : 서버측에서 실행되는 JS

UI : User Interface

API : Application Programing Interface

코드의 형태를 띄고 있는 인터페이스. ex) alert Interface

복잡한 코드를 띄고 있음에도 불구하고 API를 통해 보다 간단한 개발이 가능하도록 해주는 인터페이스.

Document → DOM (Document Object Model) → Window 순으로 서칭 범위를 넓혀가며 필요한 기능 찾기

Index | Node.js v19.4.0 Documentation


언어 - JS

  • typeof : 데이터형을 알려주는 기능 (like var_dump)
    alert(typeof "1");
  • 일치연산자
    alert(1=='1'); // true
    alert(1==='1'); // false
    // ===같은 경우 값과 데이터형이 모두 정확히 일치해야 true를 반환한다.
    -------------------------------
    alert(0 === -0); // true
    alert(NaN === NaN); // false
    -------------------------------
    alert(1!=1); // false
    alert(1!==1); // false
  • 0 : false / 나머지 : true
  • 변수 선언시 var로 한다. & for와 while문 형식은 java와 동일
    var i = 1;
    
    for(var i = 0; i < 10; i++) {
    	alert(i);
    }
    
    while(i < 10) {
    	alert(i);
    i++;
    }

함수 선언1, 2 & 익명함수

// 함수 선언 방법 1
function numbering(start) {
	while(start < 10) {
		console.log(start);
		start++;
	}
	return 'successful';
}

// 함수 선언 방법 2
numbering = function() {
	while(start < 10) {
		console.log(start);
		start++;
	}
	return 'successful';
}

// 정의와 호출을 같이 하는 방식...이름이 필요 X -> 익명함수
// 1회성으로 작성할 때 사용하는 테크닉
(function() {
	while(start < 10) {
		console.log(start);
		start++;
	}
	return 'successful';
})();

배열

  • 대괄호([])는 배열을 만드는 기호이다.
var id = ['1', '2', '3']

alert(id[0]);
alert(id[1]);
alert(id[2]);
---------------------------
// 배열에 원소 추가하기
id.push('4'); // 끝에 4 추가
id.concat(['5', '6']); // 끝에 5, 6 추가
id.unshift('0'); // 배열의 처음에 0 추가, 기존 값들의 색인(index)은 1씩 증가(shift)
id.splice(2,0,'1.5'); // 2번째 인덱스에 0개를 삭제한 후 1.5를 끼워넣는다.
---------------------------
id.pop(); // 맨 끝 원소 삭제
---------------------------
id.sort(); // 오름차순 정렬
id.reverse(); // 내림차순 정렬

객체(Object)

  • 연관배열 or 맵 or 딕셔너리와 같다.
// 객체 선언 방법1
var grades = {'a' : 88, 'b' : 89, 'c' : 90};

// 객체 선언 방법2
var grades = {};
grades['a'] = 88;
grades['b'] = 89;
grades['c'] = 90;

//객체 선언 방법3
var grades = new Object();
grades['a'] = 88;
grades['b'] = 89;
grades['c'] = 90;

//객체 호출방법
alert(grades.a); // 88
alert(grades['a']); // 88
  • 객체는 객체를, 함수를 담을 수도 있다.
var grades = {
	'list' : {'a' : 100, 'b' : 90, 'c' : 80}
	'show' : function() {
		alert('Hello world');
	}
	'this' : function() {
		alert(this); // this : 이 함수가 속해있는 객체를 가리키는 변수
	}
}

alert(grades['list']['a']); // 100
**alert(grades['show']); // function() { ~~ }
alert(grades['show']()); // Hello world**

var grades = {
	'list' : {'a' : 100, 'b' : 90, 'c' : 80}
	'show' : function() {
		for(var level in this.list) {
			console.log(level, this.list[level]);
		}
	}
}

모듈

<script src="greeting.js"> </script>

js파일을 따로 빼서 만듦으로서 유지보수에 적합하게 만든다. (모듈화)

  • 모듈 → 라이브러리 (ex) JQuery
    <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>

정규표현식

  1. 컴파일
    1. 패턴(대상)을 찾는다.
  2. 실행
    1. 추출 (exec), Test(test), 치환(replace) 등의 작업을 실행한다.
  • 자바스크립트에서의 정규표현식
    // 정규표현식 표현방법 1
    var pattern = /a/; // / 사이의 패턴을 찾는다.
    
    // 방법 2
    var pattern = new RegExp('a'); // Regular Expression(a)를 찾는 객체를 하나 만듦.
    pattern.exec('abcde'); // ['a'] // abcde 중에 a를 찾는 것. 없으면 null을 리턴.
    pattern.test('abcde'); // true - a 존재함
    pattern.test('bcde'); // false - a 존재하지 않음
    var str = 'abcdef';
    str.replace(pattern, 'A'); // 'Abcdef'
    
    var oi = /a/i; // i 는 대소문자 구분을 하지 않고 찾는다.
    var xg = /a/;
    "abcdea".match(xg); // ['a']
    var og = /a/g; // g 는 중복을 허용한다.
    "abcdea".match(og); // ['a', 'a']
    var ig = /a/ig;
    "AbcdeAa".match(ig); // ['A', 'A', 'a']
  • 캡쳐
    (\w+)\s(\w+) ... 하나 이상의 문자(a-Z,0-9)그룹 후 공백 후 하나~
    ex) A B | 0 r | 등등
    
    var pattern = /(\w+)\s(\w+)/; // $1 : coding, $2 : everybody
    var str = "coding everybody";
    var result = str.replace(pattern, "$2, $1"); // everybody, coding, 그룹을 지정하고 그 그룹을 가져와 사용한다 : 캡쳐

함수지향

var vscope = 'global';
function fscope() {
	var vscope = 'local';
	alert(vscope);
}
fscope(); // local
alert(vscope); // global

function fscope() {
	vscope = 'local';
	alert(vscope);
}
fscope(); // local
alert(vscope); // local

var를 사용하지 않고 선언하면 global 선언이 되므로 값이 변경된다.

var선언을 습관화하자. for 코드의 재사용성

유효범위의 대상

JS는 함수에 대해서만 유효 범위를 제한한다. for 문이나 기타 {} 안의 변수들은 다른 언어들과 달리 함수의 {}만 아니면 사용 가능하다는 것이다.

  • 정적(Lexical) 유효범위
var i = 5;

function a() {
	var i = 10;
	b();
}

function b() {
	alert(i);
}

a(); // 5

비동기 처리

Ajax - Asynchronous Javascript And XML

리로딩을 하지 않고 서버와 웹 브라우저가 내부적으로 소통하는 기술

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$.get(
	'http://~~',
	function(result) { // $.get이 위 url에서 가져온 데이터를 result로 function인자에 넣어줌.
		console.log(result); // 사용자에게 어떤 처리를 위임한다 -> 콜백
	}, 'json'
);
</script>

클로저

Closure

내부함수가 외부함수의 맥락에 접근할 수 있는 것을 가리킨다.

function outter() {
	var title = 'coding everybody';
	return function() {
		alert(title);
	}
}
inner = outter();
inner(); // coding everybody
function factory_movie(title) {
	return {
		get_title : function() {
			return title;
		},
		set_title : function(_title) {
			title = _title;
		}
	}
}
ghost = factory_movie('Ghost in the shell');
matrix = factory_movie('Matrix');
alert(ghost); // Ghost in the shell
alert(matrix); // matrix
var arr = []
  for(var i = 0; i < 5; i++) {
    arr[i] = function(id) {
      return function() {
        return id;
      }
    }(i);
  }
  for (var index in arr) {
    console.log(arr[index]());
  }

Arguments

유사 배열 성격을 띈 객체

  • 매개변수의 수를 나타내는 2가지 방법
    1. 함수.length : 함수에서 정의된 인자의 수를 나타냄
    2. arguments.length : 함수에 실제로 전달된 인자의 수를 나타냄

함수의 호출

  • Function.apply, Function.call
    • function.apply(맥락, 배열) 을 인자로 받는다.
    • 맥락 : 함수가 실행될 맥락을 의미한다.
      o1 = {val1:1, val2:2, val3:3}
      o2 = {v1:10, v2:50, v3:100, v4:25}
      function sum() {
      	var _sum = 0;
      	for(name in this) {
      		_sum += this[name];
      	}
      	return _sum;
      }
      alert(sum.apply(o1)); // 6
      alert(sum.apply(o2)); // 185

객체지향

이론

  • 추상화 : 복잡함 속에서 필요한 관점만을 추출하는 행위
  • 부품화가 중요한 것임에는 분명하지만 그 보다 중요한 것은 적절함이다.
  • 연관된 메소드와 그 메소드가 사용하는 변수들을 분류하고 그룹핑하는 것이다.
    바로 그렇게 그룹핑 한 대상이 객체(Object)다.
  • 즉 내부의 동작 방법을 단단한 케이스 안으로 숨기고 사용자에게는 그 부품의 사용방법만을 노출하고 있는 것이다. 이러한 컨셉을 정보의 은닉화(Information Hiding), 또는 캡슐화(Encapsulation)라고 부른다. 자연스럽게 사용자에게는 그 부품을 사용하는 방법이 중요한 것이 된다.
  • 인터페이스는 부품들 간의 약속이다.

실재

  • 객체 내 변수 : Property (Java에서는 Field)
  • 객체 내 함수 : Method
  • 생성자
    • 생성자 함수는 일반함수와 구분하기 위해서 첫글자를 대문자로 표시한다.

      function Person(name){
          this.name = name;
          this.introduce = function(){
              return 'My name is '+this.name; 
          }
      }
      var p1 = new Person('egoing'); // egoing
      document.write(p1.introduce()+"<br />");
       
      var p2 = new Person('leezche');
      document.write(p2.introduce()); // leezche
  • 자바스크립트에서 객체를 만드는 주체는 함수다. 함수에 new를 붙이는 것을 통해서 객체를 만들 수 있다.
  • 전역객체
    • JS에서 모든 객체는 기본적으로 전역 객체의 property이다. 객체를 명시하지 않으면 암시적으로 window의 프로퍼티로 간주된다. 전역객체의 이름도 호스트환경에 따라서 다른데, 웹브라우저에서 전역객체는 window이지만 node.js에서는 global이다.

      function func(){
          alert('Hello?');    
      }
      func(); // Hello
      window.func(); // Hello
      
      var o = {'func':function(){
          alert('Hello?');
      }}
      o.func(); // Hello?
      window.o.func(); // Hello?
    • 결국 함수도 전역 객체의 프로퍼티이기 때문에 여기서 this는 window라는 전역 객체를 가리킨다. Node.js에서는 global

      function func(){
          if(window === this){
              document.write("window === this");
          }
      }
      func();
  • This
    • 함수와 this : this는 함수가 소속되어 있는 객체를 가리키며 디폴트는 전역 객체를 가리키게 된다.
    • 메소드와 this : 객체 소속인 method의 this는 그 객체를 가리킨다.
      var 0 = {
      	func : function() {
      		if (o === this) {
      			document.write("o === this");
      		}
      	}
      }
      o.func();
    • 생성자와 this : new func(); → 생성자 new를 통해 객체 선언을 해준다.
      var funcThis = null;
      function Func() {
      	funcThis = this;
      }
      var o1 = Func(); // 함수 저장 -> 함수에서 this 호출 -> 전역 객체인 window
      if (funcThis === window) {
      	document.write('window </br>');
      }
      var o2 = new Func(); o2 객체 저장 -> 객체에서 메소드 호출 -> this는 o2를 가리킴
      if(funcThis === o2) {
      	document.write('o2 </br>');
      }
    • Apply와 Call
      function sum(x,y) {return x+y;}
      var sum2 = new Function('x', 'y', 'return x+y;');
      sum2(1,2); // 3
      // 함수 Literal을 만들어 준다. (리터럴:보다 편한 문법체계, 객체리터럴, 배열리터럴 등)
      var o = {}
      var p = {}
       function func() {
          switch(this) {
            case o:
              document.write('o<br />');
              break;
            case p:
              document.write('p<br />');
              break;
            case window:
              document.write('window<br />');
              break;
          }
        }
        func();
        func.apply(o);
        func.apply(p);
      // 즉, 함수는 자바와 달리 객체에 소속되지 않고, window객체, o객체, p객체에 apply된다.
  • 상속 : prototype
    function Person(name) {
        this.name = name;
      }
      Person.prototype.name = null;
      Person.prototype.introduce = function() {
          return 'My name is ' + this.name;
      }
    
      function Programmer(name) {
        this.name = name;
      }
      **Programmer.prototype = new Person();
    // 상속을 위해서는 생성자의 프로토타입에 상속받고자 하는 객체를 생성해주면 된다.
    	Programmer.prototype.coding = function() {
    		return "hello world";
    	} // 상속된 객체에서 함수를 추가한 케이스. 마찬가지로 prototype 사용.**
    
    	function Designer(name) {
    		this.name = name;
    	}
    	Designer.prototype = new Person();
    	Designer.ptototype.design = function() {
    		return "beautiful";
    	}
    
      var p1 = new Programmer('john');
      document.write(p1.introduce() + "<br />");
    	document.write(p1.coding() + "<br />");
    	var p2 = new Designer('sarah');
    	document.write(p2.introduce() + "<br />");
    	document.write(p2.design() + "<br />");
  • Prototype (원형) → 상속 지원을 위한 개념
    • 객체 안에 원하는 메소드가 존재하지 않으면, 계속해서 상위 객체로 올라가서 찾는다.
    • 이 기능이 prototype을 통해 가능해진다.
      • 생성자는 기본적으로 함수이다. 함수 앞에 new를 붙여 생성자가 만들어지며, 이렇게 콜된 값은 객체를 리턴한다.
      • func.prototype은 객체를 보유하고 있다. 즉, prototype은 객체를 가질 수 있는 funcf라는 객체의 property이다. → Prototype 체인 개념도 나올 수 있음.

표준 내장 객체의 확장

표준 내장 객체를 상속받아 커스텀 메소드들을 작성함으로서 확장을 이룰 수도 있다.

Object(Default)

모든 객체는 기본적으로 object를 상속받고 있으며, 따라서 object를 확장할 수도 있다.

hasOwnProperty는 인자로 전달된 속성의 이름이 객체의 속성인지 여부를 확인한다. 만약 prototype으로 상속 받은 객체라면 false를 리턴한다.

데이터타입

객체와 비객체(Primitive type)로 나눌 수 있다.

  • 비객체 ( = Primitive type)
    • number
    • string
    • boolean
    • null
    • undefined
  • 나머지는 객체
  • 비객체임에도 property식 접근이 가능한 이유는 “Wrapper Object” 기능 때문이다.
  • Wrapper Object
    • String, Number, Boolean이 존재한다.
    • property식 접근이 일어날 때 해당 객체를 만들어 사용한 후 바로 삭제된다.

참조

  • 비객체 (이하 primitive type) 들은 복제되지만 객체는 참조된다.
  • 객체는 다른 말로 참조 데이터형이라고도 부른다.
var a = 1;
var b = a;
b = 2;
console.log(a); // 1

var a = {'id':1}; // 데이터형이 객체이므로 참조형이다. 즉, 값이 바뀌면 같이 바뀐다.
var b = a;
b.id = 2;
console.log(a.id); // 2

var a = 1;
function func(b){
    b = 2;
}
func(a);
console.log(a); // 1

var a = {'id':1};
function func(b){
    b = {'id':2}; // b에 새로운 객체를 전달했으므로 a는 상관이 없다.
}
func(a);
console.log(a.id);  // 1

var a = {'id':1};
function func(b) {
		b.id = 2;
}
func(a);
console.log(a.id); // 2

WEB - JS

  • 이벤트 ( onclick ) 약 10~20개 정도의 이벤트를 정의해 놓았다.
    <input type="button" value="hi" onclick="alert('hi')">
  • this
    <input type="button" value="night" onclick="
      var target = document.querySelector('body');
      if(this.value === 'night') {
        target.style.backgroundColor = 'black';
        target.style.color = 'white';
        this.value = 'day';
      } else {
        target.style.backgroundColor = 'white';
        target.style.color = 'black';
        this.value = 'night';
      }
    ">
  • 함수

함수를 콜할 때 this 를 매개변수로 넣으면 이는 함수가 속한 태그를 넘긴다.

만약 매개변수가 없다면 함수 내 this는 전역 객체를 가리키게 된다.

<input type="button" value="night" onclick="
  nightDayHandler(this);
">

function nightDayHandler(self) {
      var target = document.querySelector('body');
      if(self.value === 'night') {
        target.style.backgroundColor = 'black';
        target.style.color = 'white';
        self.value = 'day';
  • 파일 정리
<script src="colors.js"> // color관련 작업 코드들을 독립 파일로 빼서 만든다.
  </script>

DOM

[JavaScript] DOM이란 무엇인가?

html을 구성하는 element들을 node 개념으로 바라보고, 더 나아가 객체로 대하는 방식

JQuery

AJAX

JSON

profile
Progress Gradually, Never Stop

0개의 댓글