DBILITY

독거 가능성 100% 노후에 라면값이라도 하게 센스를 발휘합시다!😅
Please click on the ad so that I can pay for ramen in my old age!
点击一下广告,让老后吃个泡面钱吧!
老後にラーメン代だけでもするように広告を一回クリックしてください。

javascript es6 class 본문

front-end & ui/javascript

javascript es6 class

DBILITY 2021. 10. 28. 17:17
반응형

이전엔 대충 function으로 했다고 한다.비슷한가? prototype이란 용어만 익숙하면 될 것 같다.

여기서 Person의 prototype, 말하자면 원형보단 조상(?)이 Object다.

function Person(name) {
    this.name = name;
    this.age = '김수한무 거북이와 두루비 삼천갑자 동박삭 치치카포 사리사리센타 워리워리 세브리깡 무두셀라 구름이 허리케인에 담벼락 담벼락에 서생원 서생원에 고양이 고양이엔 바둑이 바둑이는 돌돌이';
    this.sayWelcome = function () {
        console.log(`어서와~ ${this.name}님`);
    }
}

Person.prototype.sayGoodbye = function () {
    console.log(`잘가유~ ${this.name}님`);
}
Person.prototype.getAge = function () {
    return this.age;
}
Person.prototype.setAge = function (age) {
    this.age = age;
}
var child = new Person('홍길동');
child.sayWelcome();
child.sayGoodbye();
console.log(child.age);
child.setAge(1000);
console.log(child.getAge());

es6부터는


class Class {
    constructor(name) {
        this.name = name;
        this.age = '김수한무 거북이와 두루비 삼천갑자 동박삭 치치카포 사리사리센타 워리워리 세브리깡 무두셀라 구름이 허리케인에 담벼락 담벼락에 서생원 서생원에 고양이 고양이엔 바둑이 바둑이는 돌돌이';
    }

    sayWelcome() {
        console.log(`어서와~ ${this.name}님`);
    }

    get getAge(){
        return this.age;
    }

    set setAge(age){
        this.age=age;
    }
}

var child = new Class('홍길동');

console.log(child);
child.sayWelcome();
console.log(child.__proto__);
console.log(Object.getPrototypeOf(child));

var parent = Object.getPrototypeOf(child);
console.log(parent);

Class.prototype.printAge = function () {
    console.log(`${this.name} 님의 나이는 ${this.age}와 같습니다.`);
};
child.printAge();

특별한 것은 없다. prototype은 말 그대로 원형이니 알 것이고 get, set은 느낌적 느낌대로 getter, setter로 사용 시 속성처럼 () 없이 사용 가능하다. 상속은 java처럼 생각한 그대로 extends를 사용한다.

class ClassChild extends Class {
    constructor(name,age) {
        super(name);
        this.age = age;
    }

    sayWelcome() {
        super.sayWelcome();
        console.log(`꺼져~ ${this.name}님`);
    }
}

var extendClass = new ClassChild("아부지",5000);
console.log(extendClass);
console.log(extendClass.getAge);
extendClass.setAge = "비밀~"
console.log(extendClass.getAge);

 

es6_006.html
0.00MB

반응형
Comments