개인공부/javascript 16

기명함수와 무명함수

* 기명함수 :  함수 자체에 이름이 있는 함수. 함수 표현식에서 기명함수를 사용할 경우, 함수 이름은 함수 내부에서만 유효 ex)  function greet() {     console.log("Hello, World!"); } greet(); ex)  const greeting = function greet() {     console.log("Hello, World!"); }; greeting();greet(); // 에러   * 무명함수 : 이름이 없는 함수. 변수에 할당될 경우, 변수명을 통해 호출 가능.주의) 함수 자체에는 이름이 없지만, 이를 변수에 할당하여 변수명을 통해 호출할 수 있다는 점 ex)  const greeting = function() {       console.log("..

8-1. Promise, Async-Await

* Callback 예시 const a = (callback) => { setTimeout(() => { console.log("1"); callback(); //콜백 지옥 발생 }, 1000); }; const b = () => console.log("2"); a(() => { b(); }); * Promise 예시 const a = () => { return new Promise((resolve) => { //Promise클래스 사용 //매개변수 resolve setTimeout(() => { console.log("1"); resolve(); //콜백이 실행 되는 부분에 호출 // resolve가 호출되는 부분은 숫자 1 출력한 다음에 실행위치를 보장하는 부분 //Promise를 사용하고자 하는 것..

getElementById와 querySelector의 차이점

js프로젝트에서 querySelector를 getElementById로 바꿔 사용하라는 피드백을 받아 찾아보게 되었다. 1. getElementById() element = document.getElementById('some-id'); // 오직 id 속성에 따라 요소를 선택. // 단일 요소 또는 null을 반환 // id 속성은 유일하기 때문에 매우 빠르게 요소를 찾을 수 있음 2. querySelector() element = document.querySelector('.some-class'); element = document.querySelector('#some-id'); // CSS 선택자를 사용하여 요소를 선택. 이로 인해 복잡한 선택 작업이 가능. // CSS 선택자와 일치하는 첫 번째 ..

7-2. js 기초 : 표준 내장 객체 (.toFixed(), Number.parseInt(), Math.abs(), ...)

* .toFixed() : 숫자를 지정된 고정 소수점 표기까지 표현하는 문자로 반환 const num = 3.14159265; console.log(num.toFixed(2)); //3.14 -> 문자 console.log(typeof num.toFixed(2)); //string console.log(parseFloat(num.toFixed(2))); //3.14 -> 다시 숫자로 변환 console.log(typeof parseFloat(num.toFixed(2))); //number console.log(num); * .toLocaleString() : 숫자를 현지 언어 형식의 문자로 반환 //ex. 사용자에게 크기가 큰 숫자를 보여줄때, 비교적 손쉽게 읽을수 있도록 쉼표 붙여주는 작업 함 cons..

7-1. js 기초 : 표준 내장 객체 (.indexOf(), .padEnd(), .split(), .trim(), .join()...)

* .length:문자의 길이를 반환 const str = "hello world"; console.log(str.length); /11 * .includes() : 대상 문자에 주어진 문자가 포함되어져있는지 확인 const str = "hello world"; console.log(str.includes("hello")); //true console.log(str.includes("Hello")); //false -> 대소문자 구분 console.log(str.includes("hello", 0)); //0번째 지점부터 확인, true console.log(str.includes("hello", 1)); //false * .indexOf() : 대상 문자에서 주어진 문자와 일치하는 첫번째 인덱스 반환,..

6-3. js 기초 : 상속, instanceof, constructor

* 상속 ex 1. class A { constructor() {} } class B extends A { constructor() { super(); } } class C extends B { constructor() { super(); } } const a = new A(); //new 키워드와 함께 호출하는 A라는 클래스는 생성자함수라고 부름 //그렇게 나오는 결과 변수 a는 하나의 인스턴스 const b = new B(); const c = new C(); console.log(a instanceof A); console.log(a instanceof B); //false console.log(c instanceof A); console.log(c instanceof B); console.log(..

6-2. js 기초 : getter/setter 함수, 프로토타입 메소드/정적 메소드

class User { constructor(first, last) { this.firstName = first; this.lastName = last; //this.fullName = `${first} ${last}`; //* 치명적인 단점: new라는 키워드로 생성자함수가 호출할때 최초로 만들어지고 //그 다음부터는 값이 바뀌어도 변화없음 } getFullName() { return `${this.firstName} ${this.lastName}`; } } const min = new User("min", "kim"); //생성자함수 console.log(min.getFullName()); min.firstName = "seo"; console.log(min.getFullName()); -> clas..

6-1. js 기초 : 프로토타입과 ES6 클래스문법의 차이

* 프로토타입과 ES6 클래스문법의 차이 //프로토타입 방식 function User(first, last) { this.firstName = first; this.lastName = last; } User.prototype.getFullName = function () { return `${this.firstName} ${this.lastName}`; }; const min = new User("min", "kim"); const yoon = new User("yoon", "hwang"); console.log(min); console.log(yoon.getFullName()); //ES6 클래스 방식 class User { constructor(first, last) { this.firstName =..

5-1. ⭐ this 추가개념

// 메소드 this : 해당 객체 참조 const audio = { title: "a", play() { console.log("play this", this); }, }; audio.stop = function () { console.log("play this", this); }; audio.stop(); // 함수 this : 윈도우 객체 참조 (윈도우객체는 브라우저에서 출력(자바스크립트 아님)) function playAudio() { console.log(this); } playAudio(); //생성자 -> 대문자로 씀 //처음에 빈 객체를 가리킨 후 a가 들어가는 순서 function Audio(title) { this.title = this; console.log(this); } const..

6. js 기초 : prototype이란?

자바스크립트 : 프로토타입 기반 언어, 클래스 기반은 아니지만 클래스 사용은 가능 //const fruits=['apple','banana','cherry'] //배열 리터럴 과 같은 결과 만들기 ex. const fruits = new Array("apple", "banana", "cherry"); //생성자 함수 //생성자 함수에서 반환된 하나의 인스턴스라고 볼 수 있음 console.log(fruits); //["apple", "banana", "cherry"] console.log(fruits.length); //3 * Array.prototype.includes("") : 배열데이터에 특정한 아이템이 들어있는지 확인 하는 메소드 ex. console.log(fruits.includes("bana..