class
ecma6 버전에서 추가된 문법
function Person(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);
kim.sum = function(){
return 'this : '+(this.first + this.second);
}
let lee = new Person('lee',10, 10);
console.log("kim.sum()", kim.sum());
console.log("lee.sum()", lee.sum());
이렇게 레거시 코드를 준비했다. prototype
으로 된 문법의 코드이다.
이를 class로 바꾸기 위해 우선
function Person(name, first, second){
this.name=name;
this.first=first;
this.second = second;
}
이 부분을
class Person{
}
이렇게 바꿔준다. class
로 객체를 생성한 것
일단 객체의 초기값을 실행하게하는 함수인constructor를 사용.
class Person{
constructor(name, first, second){
this.name=name;
this.first=first;
this.second = second;
}
}
classs에서는
function
을 쓰지 않고 바로 sum() 이런식으로 사용한다.
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();
console.log('kim', kim)
kim.sum = function(){
return 'this : '+(this.first + this.second);
}
이런식으로 안에 함수를 구현하고, 밖에다 프로토타입 써서 구현해도 된다. 만약 kim
에만 적용하고 싶으면 밖에 따로 빼서 kim.sum이라는 함수를 만들어 줘도 된다.