생성자 함수
function Shape(width, height) {
this.width = width;
this.height = height;
}
Shape.prototype.getArea = function () {
console.log('i`m Shape Prototype');
return this.width * this.height;
};
const rect1 = new Shape(10, 10);
console.log(rect1.getArea());
console.log(rect1);
프로토타입
프로토타입 객체는 생성자 함수의 prototype 속성으로 접근하여 확인할 수 있고 생성자 함수로 만들어낸 객체에서는 proto 속성으로 접근하여 확인할 수 있다. 즉 생성자 함수로 생성된 모든 인스턴스에서 공유가 된다.
function MakeAnimalObject(){
this.animalName = "곰";
this.animalType = "고양이";
this.animalAge = 8;
this.animalGender = "male";
this.lastVisit = "2023-08-11";
this.getLastMedical = function(){
return this.animalName+"는 " + this.lastVisit + "에 마지막으로 진료받았습니다.";
}
}
let animal1 = new MakeAnimalObject();
let animal2 = new MakeAnimalObject();
console.log(animal1 === animal2); // false;
console.log(animal1.__proto__ === animal2.__proto__); // true;
< __proto__ 속성 접근 차이 >
animal1.getName = function() {
return `이름은 ${this.animalName}입니다.`
};
console.log(animal1.getName()); // 이름은 곰입니다.
console.log(animal2.getName()); // animal2.getName is not a function
animal1.__proto__.getName = function() {
return `이름은 ${this.animalName}입니다.`
};
console.log(animal1.getName()); // 이름은 곰입니다.
console.log(animal2.getName()); // 이름은 곰입니다.
class
class Shape1 {
constructor(color) {
this.color = color;
}
getColor() {
return this.color;
}
}
const shapeClass = new Shape1('red');
console.log(shapeClass.getColor());
class Rectangle extends Shape1 {
// 상속을 하든, 상속을 안하든 반드시 constructor를 가지고 있어야 한다.
constructor(color, width, height) {
super(color); // 부모 클래스 constructor를 호출하기 위함
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
const rect9 = new Rectangle('blue', 10, 20);
console.dir(rect9.getColor());
console.log(rect9.getArea());
class Car {
constructor(speed) {
this.speed = speed;
}
get speed() {
return this._speed; // 같은 이름에 할당되면 무한루프에 빠지게 됨 그래서 언더바(_speed)를 사용하는게 관례이다
}
set speed(value) {
this._speed = value < 0 ? 0 : value; // speed는 음수가 될 수 없으니 조건 처리
}
getSpeed() {
return this.speed;
}
// 가정... 수많은 함수들이 구현되어 있다.
// 가정... 그 수많은 함수에서 speed를 사용하고 있다.
}
const car1 = new Car(-100);
console.log(car1.getSpeed());
클로저
const a = 1;
function outer() {
const b = 2;
function inner() {
console.log(b);
}
return inner;
}
const innerFunc = outer();
innerFunc(); // 2
위 코드를 보면 먼저 outer 함수가 호출되면 새로운 실행 컨텍스트가 생성된다. 그리고 inner 함수를 반환한다.
inner 함수를 반환했으니 outer 함수는 생명주기가 종료되어 실행 컨텍스트 스택에서 제거된다.
inner 함수는 outer 함수의 렉시컬 환경을 클로저로서 참조하고 있어서 inner 함수가 외부 변수 b에 접근할 수 있어 2가 출력된다.
Dom
// id
document.getElementById(id);
document.querySelector("#id");
// 태그
document.getElementsByTagName(name);
// 클래스
document.getElementsByClassName(class)
document.querySelector(".class")
document.querySelectorAll(".class") // 복수 선택
// 스타일 변경
document.getElementById(id).style.color = "변경할 color";
// 속성 추가 및 제거
document.getElementById(id).setAttribute("속성명", "속성값");
document.getElementById(id).removeAttribute("속성명");
// 콘텐츠 조작
document.getElementById(id).innerHTML = "새로운 내용"
document.getElementById(id).innerText = "새로운 텍스트"
[문제1]
매개변수로 숫자를 전달하면 그 숫자의 역순을 되돌려주는 함수를 만들어주세요.
ex) 32125 -> 52123
15231 -> 13251
function reverse_to_number(number) {
// 풀이1
// return Number(number.toString().split('').reverse().join(''));
// 풀이2
let str = number.toString().split('');
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
result += str[i];
}
return Number(result);
}
let a = reverse_to_number(32125);
console.log(a); // 52123
let b = reverse_to_number(13251);
console.log(b); // 15231
[문제2]
가장 긴 단어를 출력하기
function findLongStr(str) {
let check = str.split(' ');
// 풀이1
// let maxLength = '';
// for (let i = 0; i < check.length; i++) {
// if (check[i].length > maxLength.length) {
// maxLength = check[i];
// }
// }
// return maxLength;
// 풀이2
// return check.reduce((acc, el) => (el.length > acc.length ? el : acc), '');
// 풀이3
return check.sort((a, b) => a.length - b.length).pop();
}
let result = findLongStr('we are the champion');
console.log(result); // champion
let result2 = findLongStr('i`m fine thank you, and you?');
console.log(result2); // thank
/*
[문제]
매개변수로 숫자를 전달하면 그 숫자의 역순을 되돌려주는
함수를 만들어주세요.
ex) 32125 -> 52123
15231 -> 13251
*/
function reverse_to_number(number) {
// 풀이1
// return Number(number.toString().split('').reverse().join(''));
// 풀이2
let str = number.toString().split('');
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
result += str[i];
}
return Number(result);
}
console.log(reverse_to_number(32125)); // 52123
console.log(reverse_to_number(13251)); // 15231
/*
[가장 긴 단어를 출력하기]
매개변수로 전달된 문장에서 가장 긴 단어를 출력해주세요.
*/
function findLongStr(str) {
let check = str.split(' ');
// 풀이1
// let maxLength = '';
// for (let i = 0; i < check.length; i++) {
// if (check[i].length > maxLength.length) {
// maxLength = check[i];
// }
// }
// return maxLength;
// 풀이2
// return check.reduce((acc, el) => (el.length > acc.length ? el : acc), '');
// 풀이3
return check.sort((a, b) => a.length - b.length).pop();
}
console.log(findLongStr('we are the champion')); // champion
console.log(findLongStr('i`m fine thank you, and you?')); // thank
오늘 수업한 개념들은 나에게 부족했던 부분의 내용들을 다시 짚어보고 채워나갈 수 있어서 좋았다. 계속 다시 반복하여 살펴보면서 동작 원리에 대해 이해하려고 한다.