이론/JS
[JS] class - 강의
millfeel1298
2021. 2. 11. 01:39
# 02:27
좌측 코드 리뷰 시작
# 03:03
생성자 함수가 하는 일
- 객체를 만든다.
- 객체의 초기 설정을 한다.
# 03:22
class 설명 시작
class는 객체를 만드는 공장이다.
class Person{
}
let kim = new Person();
# 04:17
생성자 함수는 객체가 만들어지는 깔끔한 객체가 아니라, 그 객체가 기본적으로 가지고 있어야할 기능들을 셋팅해주는 기능도 생성자 함수가 해야하는 일이었다.
function Person(){
this.name= name;
this.first= first;
this.second= second;
}
# 00:22
class에서 메서드를 만들 때, function을 사용하지 않는다.
class Person{
function sum(){} // ------------------------------ X
sum(){} // --------------------------------------- O
}
# 00:58
객체가 생성될 때 그 객체의 초기 상태를 지정하기 위한 객체가 만들어지기 직전에 실행되도록 약속되어 있는 함수
class Person{
constructor(){
console.log('constructor');
}
}
let kim = new Person();
new Person()이 실행되면 자동으로 constructor 메서드가 실행된다.
# 02:02
class Person{
constructor(name, first, second){
this.name= name;
this.first= first;
this.second= second;
}
}
let kim = new Person('kim', 10, 20);
# 00:14
생성자 함수의 prototype 객체에 함수를 추가함으로써 모든 객체가 공유하는 함수를 만들었다.
# 00:40
class로 모든 객체가 공유하는 함수 만드는 첫번째 방법
class Person{
constructor(name, first, second){
this.name= name;
this.first= first;
this.second= second;
}
}
Person.prototype.sum = function(){
return 'prototype: ' + (this.first + this.second);
}
let kim = new Person('kim', 10, 20);
*모든 함수는 prototype 프로퍼티를 가지고 있기 때문에 생성자 함수와 동일한 방법이 적용된 것이다.
* class는 함수다.
# 01:18
sum 함수를 calss 안에 넣을 수도 있다.
class Person{
constructor(name, first, second){
this.name= name;
this.first= first;
this.second= second;
}
sum(){
return 'prototype: ' + (this.first + this.second);
}
}
let kim = new Person('kim', 10, 20);
console.log('kim.sum()', kim.sum());
# 01:38
sum 함수는 같은 class에 속해있는 모든 객체들이 사용하는 함수이다.
검증을 위해서 lee 객체를 만들어서 sum 함수 사용
let lee = new Person('lee', 10, 10);
console.log('lee.sum()', lee.sum());
# 02:06
kim 객체만 다르게 동작하는 sum 함수를 만들고 싶을 때
kim.sum = function(){
return 'this: ' + (this.first + this.second);
}
[공부 좌표]