[ES6+] 클래스의 확장 extends


this

클래스 내의 this 는 클래스 그 자체를 가리킨다

class User{
	construntor(name){
		this.username = name;
    this.lastName = lastName;
    this.email = email;
    tihs.password = password;
	}
  sayHello(){
    console.log(`hi my name is ${this.username}`);
  }
}
const sexyUser = new User("sora","ji","wlthfk0211@gmail.com","1234");



아래와 같이 data를 불러오거나 변경하거나 할 수 있다

class User{
	construntor(name){
		this.username = name;
    this.lastName = lastName;
    this.email = email;
    tihs.password = password;
	}
  sayHello(){
    console.log(`hi my name is ${this.username}`);
  }
  updatePassword(newPassword, currentPassword){
    if(currentPassword === this.password){
      this.password = newPassword;
    }else{
      console.log("can't change password");
    }
  }
}

const sexyUser = new User("sora","ji","wlthfk0211@gmail.com","1234");
console.log(sexyUser.password);
sexyUser.updatePassword("hello","1234");
console.log(sexyUser.password);
//1234
//hello

console.log(sexyUser.password);
sexyUser.updatePassword("hello","11111");
console.log(sexyUser.password);
//1234
//can't change password
//1234




extend

새로운 클래스를 만들건데, 새로만들 클래스가 기본의 클래스의 속성을 다 가지고 시작했으면 좋겠을때 extend를 쓴다

class Admin extends User{
  deleteWebsite(){
    console.log("delete website...")
  }
}

const sexyAdmin = new Admin();
sexyAdmin.deleteWebsite();
//delete website...

console.log(sexyAdmin.email);
//undefined (이유는 constructor에 아무것도 작성하지 않아서이다)


//만약 constructor를 이용하게되면 값을 돌려줄 수 있다
const sexyAdmin = new Admin("sora","ji","wlthfk0211@gmail.com","1234");
console.log(sexyAdmin.email);
//wlthfk0211@gmail.com

다음편에 계속!





노마드코더의 ‘ES6의 정석’을 듣고 정리 =)




© 2018. by sora

Powered by sora