📌 학습한 내용


전체 코드 1 : 💾

생성자 함수 (클래스)

: 공통된 요소들을 묶어내는 일종의 박스

  • 객체지향 프로그래밍 (OOP - Object Oriented Programming)과 밀접한 관계

  • (기능을 만들 때 사용하는) 일반 함수와 구분하기 위해 첫 글자를 대문자로 작성

// 생성자 함수 (붕어빵 틀에 비유)
function Heroes(name, age) {
	this.name = name;
	this.age = age;
} // this 자체가 인스턴스를 가리키고 있는 것

// 인스턴스 = new 생성자 함수명(매개변수) 
var superMan = new Heroes('슈퍼맨', 30);
var blackWidow = new Heroes('블랙위도우', 34);
  • 인스턴스 : new 키워드를 이용해 생성자 함수를 호출한 결과값이 담겨진 결과물 (붕어빵에 비유)

생성자 함수 내에서 메서드 정의

function Person(firstName, lastName) {
	this.firstName = firstName;
	this.lastName = lastName;
	
  	// 인스턴스가 활용할 메서드 정의
	this.fullName = function() {
		console.log(this.firstName + " " + this.lastName);
	}
}

var jeong = new Person("Jane", "Jeong");
var park = new Person("David", "Park");

console.log(jeong);
console.log(park);

jeong.fullName();
park.fullName();

  • 인스턴스 자체도 객체와 같은 구조를 가지고 있음

프로토타입 (Prototype)

: 생성자 함수 안에서 모든 인스턴스에 공통적으로 적용되는 메서드가 존재할 경우 사용

각각의 jeong과 park이라는 인스턴스에서는 firstName과 lastName에 서로 다른 키값이 들어가 있다. 하지만 fullName에 대해서는 동일한 값을 가지고 있다.
-> 같은 코드가 반복적으로 노출되는 상황
-> 불필요한 메모리를 차지

👉 Person 생성자 함수를 만들 때, Person.prototype 객체가 같이 생성된다.

// 조상 (Person.prototype)  
function Person(firstName, lastName) {
	this.firstName = firstName;
	this.lastName = lastName;
}

//Person.prototype 객체에 'fullName' 이라는 메서드를 추가한 것 (조상에게 기술을 부여한 것)
Person.prototype.fullName = function() { 
	console.log(this.firstName + " " + this.lastName);
}

// 후손(인스턴스 자체) - 조상에게 부여한 기술을 가져다 사용o , 가지고 있는 것은 x -> 불필요한 메모리를 가지지 x
var jeong = new Person("Jane", "Jeong");
var park = new Person("David", "Park");

jeong.fullName();
park.fullName();

인스턴스가 어떤 프로토타입으로 부터 영향을 받는 것인지 식별하는 방법

// 배열을 만드는 방법
var arr1 = [];
var arr2 = new Array();  
  • Array() : 자바스크립트에서 만들어 놓은 배열을 만드는 생성자 함수, 데이터가 들어갈 자리를 미리 만들어 놓음 (비어있는 데이터)
// 문자열을 만드는 방법
var str1 = "Hello";
var str2 = new String("Nice");
  • String() : 자바스크립트에서 만들어 놓은 문자열을 만드는 생성자 함수. 단, 만들어진 데이터 타입은 객체.
//함수를 만드는 방법
var func1 = function() {
}
var func2 = new Function("x, y", "return x * y");
console.log(func2);
  • Function() : 자바스크립트에서 만들어 놓은 문자열을 만드는 생성자 함수.

=> arr2, str2, func2 = 인스턴스

  • console.dir() : 인자의 내부 구조를 좀 더 디테일하게 확인하고자 할 때 사용

__proto__

: 인스턴스의 조상(프로토타입 객체)을 알아낼 때 사용되는 프로퍼티

var person = new Object();
console.log(person);

person.name = "Jane";  // 새로운 프로퍼티 추가 가능
person.sayHi = function() {
	console.log("hi"); 
}  // 새로운 메서드 추가 가능

console.log(person);
console.log(person.__proto__ === Object.prototype);
// -> person의 조상이 Object.prototype 객체가 맞는가?
// output = true
  • Object.prototype : 모든 자바스크립트 객체의 조상

constructor

: 인스턴스의 생성자 함수를 알아낼 때 사용되는 프로피터

  • 모든 생성자 함수의 프로토타입 객체는 Function.prototype 객체

  • .prototype객체가 들어가 있는 것은 객체, 생성자 함수 명만 있는 것은 생성자 함수

Person.prototype // 프로토타입 객체
Person // 생성자 함수

전체 정리

// 생성자 함수
function Person(firstName, lastName) {
	this.firstName = firstName;
	this.lastName = lastName;
}

// 인스턴스 
var jeong = new Person("Jane", "Jeong")

console.log(jeong);
console.log(jeong.__proto__ === Person.prototype);  // true
console.log(Person.prototype.__proto__ === Object.prototype);  // true
console.log(jeong.__proto__ === Object.prototype);  // false -> 중간 단계의 조상을 띄어넘는 것은 x

console.log(Person.__proto__ === Function.prototype); // true 모든 생성자 함수의 직계 조상은 Function.prototype 객체
console.log(Function.prototype.__proto__ === Object.prototype); // true

console.log(jeong.constructor === Person);  // true
console.log(Person.prototype.constructor === Person);  // true

this

: this가 어디에 포함되어 있는가에 따라서 가리키는 대상이 매번 달라짐 (코드를 간소화 하기 위해 주로 사용)

1. 일반 함수 this / 중첩 함수 this : window (브라우저)

  • 중첩으로 들어가 있는 함수 안에서의 this는 무조건 window
function a() {
	function b() {
		console.log(this);
	}
	b();  // window
}
a();  // window

2. 이벤트에서의 this : 이벤트 객체

var prevBtn = document.querySelector('.prevBtn');

prevBtn.addEventListener('click', function() {
	console.log(this);  // prevBtn
})

3. (객체안에 있는) 메서드 안에서의 this : 객체

var obj = {
	age: 100,
	sum: function() {
             console.log(this);  // obj 자체
	}
}
obj.sum();

4. 메서드 안에 함수(중첩함수)가 들어가 있는 경우 this : window(브라우저)

var obj = {
	age: 100,
	sum: function() {
             // console.log(this);  // obj 자체
	     
      	     function a() {
		console.log(this); // window 
	     }
		a();
	}
}
obj.sum();

5. 중첩 함수안의 this도 obj(객체)를 가리키게 하고 싶을 때 : 변수 that에 this를 저장

var obj = {
	age: 100,
	sum: function() {
		var that = this; // sum 안에서의 this는 obj를 가리킴 -> that에는 obj가 들어가게 됨
		function a() {
			console.log(that); 
		}
		a();
	}
}
obj.sum();

템플릿 리터럴 (Template Literal)

: `(벡틱)으로 문자열을 만들 수 있음, 변수 안의 값을 특정 문자열 안에 다이렉트로 삽입하고자 할 때 사용 (ES6 버전부터 도입)

  • 백틱 안 문자열을 쓰고, ${}안에 자바스크립트 일부 코드(변수)를 작성할 수 있다.
var name = "jane";

console.log("내 이름은" + " " + name + "입니다.");
console.log(`내 이름은 ${name}입니다.`);

실습

1. 생성자 함수 활용하기

  • '210831 개발일지' 의 4번 실습 코드 중, 이미지 정보 리스트를 생성자 함수로 생성
var arr = [];
var i = 0;

// 생성자 함수
function PuppyPicture(name, img, txt) {
	this.name = name;
	this.img = img;
	this.txt = txt;  // 매개변수 값 할당
}

function creatPuppyPicture(name, img, txt) {
	var fullImg = `img/img-${img}.jpg`;
	var puppy = new PuppyPicture(name, fullImg, txt);  // 이미지 인스턴스
	arr.push(puppy); // 객체 결과물을 배열 안쪽의 데이터로 넣어줌
}

creatPuppyPicture("puppy 1 name", 0, "puppy 1 description");
creatPuppyPicture("puppy 2 name", 1, "puppy 2 description");
creatPuppyPicture("puppy 3 name", 2, "puppy 3 description");
creatPuppyPicture("puppy 4 name", 3, "puppy 4 description");  // 위의 매개변수에 각각 할당

console.log(arr);


전체 코드 2 : 💾

2. 무한 루프

  • % (나머지 반환) 특성을 이용해 'current'가 배열의 인덱스값 안에서 무한 반복되도록 설정

  • setTimeout(함수, 시간) : 타이머가 만료된 지정된 함수 실행

unction loop() {

	var current = index % arr.length;  // 최초값 0 % 3 = 0, arr.length = 고정값
	console.log(arr[current]);
	index++ // 호출될 때 마다 index값은 1씩 증가

	setTimeout(function() {
		loop();
	}, 1000); // 1초마다 function()이 실행되게 함
}

loop(); // 최초 loop는 실행

3. 배열 안의 텍스트 데이터 한 글자씩 생성/삭제 반복

1. html 작성 후, js 파일 연결 -> 작업할 html 태그와 노출시킬 텍스트 리스트 작성

<body>
	<h1 id="txt"></h1>
	<script src="js/main.js"></script>
</body>
// 이벤트를 설정할 html 태그 가져오기
var txtElement = document.getElementById('txt');
// 이벤트 실행시 호출할 함수 생성
var words = ["엔드게임", "인피니티 워", "에이지 오브 울트론"];

2. 생성자 함수 생성, 호출

//생성자 함수
function TypeWriter(txtElement, words) {
	this.txtElement = txtElement;  // txt
	this.words = words;  // words 함수

	// 글자가 하나씩 완성되는 영역
	this.txt = ""; // 출력될 글자들이 들어갈 위치
	this.wordsIndex = 0; // 기준점
	this.isDeleting = false;
  // 기준점2 - 현재 상태(삭제중/작성중), 처음에는 작성 중이기 때문에 false 기본값으로 넣어줌

	this.type();
}

TypeWriter.prototype.type = function() {
}

new TypeWriter(txtElement, words); 
// 생성자 함수 호출시, 인스턴스가 반드시 필요한 것은 x

3. type 메서드 생성

1) 현재 배열안에 있는 데이터 가져오기

TypeWriter.prototype.type = function() { 
  
	var current = this.wordsIndex % this.words.length; 
	// 최초값 0 % 3 = 0
	var fullTxt = this.words[current]; 
	// 현재 current에 있는  값을 기준으로 배열 안의 데이터를 가져온다

2) this.isDeleting = true / false 로 분기처리

  • substring(시작점, 끝점) : string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환
    substring(n) : n번째부터 시작하는 부분 잘라내서 반환
if(this.isDeleting) {
	// 엔드게임 -> 엔드게
	// 엔드게 -> 엔드 ...
	this.txt = fullTxt.substring(0, this.txt.length - 1);

} else {
	// "" -> 엔
	this.txt = fullTxt.substring(0, this.txt.length + 1); // 0번째 부터 txt현 상태에 대한 length에 +1 까지
}

this.txtElement.textContent = this.txt; //h1 태그에 노출

3) 텍스트가 완성되었을 때 / 텍스트가 모두 삭제되었을 때로 분기처리

if(!this.isDeleting && this.txt === fullTxt) {	
	this.isDeleting = true;
  
}  else if(this.isDeleting && this.txt === "") {
	this.isDeleting = false;
	this.wordsIndex++ // 다음 텍스트로 넘어가기
}

4) 0.4초 마다 자기자신 호출

var that = this 
// this.type(); 이 window를 가리키는 것을 막기 위해 
// (중첩 함수의 this의 대상을 해당 객체자체로 바꾸기 위해)

// 자기자신(TypeWriter.prototype.type) 다시 호출
setTimeout(function() {  
		that.type();

	}, 400);

📌 학습내용 중 어려웠던 점


  1. __proto__[[prototype]]의 차이점
    강사님과 동일하게 작성한 코드를 개발자 도구에서 확인했을 때, __proto__ 가 아닌 [[prototype]]으로 나타남.

📌 해결방법


  1. 인터넷 서칭 결과
    [[prototype]]이 Prototype Object이고 __proto__는 Prototype Link라고 한다.
    (참고 사이트 : https://okayoon.tistory.com/entry/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85Prototype%EC%9D%B4%EB%9E%80-%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85%EB%A7%81%ED%81%ACPrototype-Link%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85%EA%B0%9D%EC%B2%B4Prototype-Object)

📌 학습소감


오늘은 일지 정리를 하는 데에도 고민을 많이 했다. 특히 마지막 실습에서는 배운 내용들이 모두 등장했는데 어떤식으로 나눠서 작업해야 다시 봤을 때 이해할 수 있을지 생각했다. html이나 css에서는 등장하는 개념들이 어려운 부분은 많이 없었는데, 자바스크립튼는 개념 자체와 단어가 명확하게 정의되지 않아서 더 헷갈리는 것 같아. 😵

profile
늘 새로운 배움을 추구하는 개린이 🌱

0개의 댓글