// class 의 새로운 상자 생성
class Toy {
constructor(name) {
this.name = name;
}
play() {
console.log(this.name + "와 함께 놀기!");
}
}
// 지정
const toy1 = new Toy("Teddy Bear");
const toy2 = new Toy("Toy Car");
// 출력
toy1.play(); // "Teddy Bear와 함께 놀기!" 출력
toy2.play(); // "Toy Car와 함께 놀기!" 출력
const daldaro = {
firstName: 'Daldaro',
lastName: 'Kim',
getFullName: function () {
return '${this.firstName} ${this.lastName}' // this 부분을 daldaro 라고 해도 무방하다.
}
}
console.log(daldaro)
new 로 시작하는 함수는 반드시 대문자로 시작하는 이름을 가져야함
new 를 호출을 하면 { } 비어있는 객체가 생성됨예시 1번
function Toy(name) {
this.name = name;
}
const teddyBear = new Toy("Teddy Bear");
예시 2번
function person(name, age) {
this.name = name;
this.age = age;
this.getName = () => {
return this.name;
}
}
class Woman {
constructor(name, age) { // class 와 constructor(생성자) 는 필수로 묶여있어야함
this.name = name;
this.age = age;
}
}
getName () {
return this.name;
}
getAge = () => {
return this.age;
}
// p = person 함수의 instance
const p = new Person('달다로', 95); // person 과 woman 은 생성자함수 라고 부름 (하나의 객체데이터를 생성함)
const p1 = new Woman('달다로', 95);
console.log(p);
console.log(p.getName());
function User(first, last) {
this.firstName = first
this.lastName = last
}
User.prototype.getFullName = function () { // user가 포함된 모든 것들은 그 안의 함수를 사용할 수 있음
return `${this.firstName} ${this.lastName}`
}
const daldaro = new User('Daro', 'Dal')
console.log(daldaro.getFullName())
function 은 생략 가능하다.Class User {
constructor(first, last) {
this.firstName = first
this.lastName = last
}
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
const daldaro = new User('Daro', 'Dal')
console.log(daldaro.getFullName())
정의
function (함수랑 클래스 둘다 가능)
object.create (최상위부모, 모든 오브젝트들은 기본적으로 prototype 을 가지고 있다.)
JS
// 큰상자 class ToyBox {...}
class ToyBox {
constructor() {
this.toys = [];
}
addToy(toy) {
this.toys.push(toy);
}
listToys() {
return this.toys;
}
// 작은 장난감 상자 class ToyBox {... class Toy {...}}
class Toy {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
}
const myToyBox = new ToyBox();
const teddyBear = new ToyBox.Toy("Teddy Bear");
const toyCar = new ToyBox.Toy("Toy Car");
myToyBox.addToy(teddyBear);
myToyBox.addToy(toyCar);
console.log(myToyBox.listToys().map(toy => toy.getName()));
// ['Teddy Bear', 'Toy Car'] 출력
마치 집 전체를 나타내는 큰 상자이다.
우리가 사용하는 다양한 기능이 있다.