[Vanilla JS] ES6 문법 - 2 -

P1ush·2021년 6월 1일
0

TIL Vanilla JS

목록 보기
2/6

공부 날짜 : 2021-06-01

참고자료


화살표함수 this

const my = {
    age: 20,
    name: 'dave',
    details:{
        hobby: 'coding',
        major: 'korea',
        // getHobby: function(){
        //     return this.hobby; //this로 hobby 불러오기.
        // }
        getHobby: () => 'coding' // 화살표 함수는 this를 사용할 수 없음.
    }
};

console.log(my.details.getHobby());

화살표 함수는 자신만의 this를 생성하지 않기 때문에, this를 같이 사용할 수 없습니다.
즉, 메소드 함수가 아닌곳에 사용하는게 적합하다고 볼 수 있습니다.


new object()

const abc = new Object();

abc.age = 10;
abc.name = 'dave';
abc.fuc03 = () => 1+2;

console.log(abc.age,abc.name,abc.fuc03());

new object()는 빈 객체를 먼저 만든 후 만든 빈 객체에다가 프로퍼티나 메소드 등을
추가하는 방식입니다. 물론 이 방법은 현재는 잘 사용되지 않는 방법입니다. 아래 코드처럼 굳이 new object()를 쓰지 않고도 가능하니까요.

// 빈 객체에 프로퍼티와 메소드 추가
const empty = {};
empty.name = 'dave';
empty.age = 10;
empty.get_data = () => {
    return 1 + 2;
}

new()

function fuc04(age,name){
    this.age = age; //선언될 데이터들은 객체이기 때문에 this로 써줘야함. (let , const X)
    this.name = name;
    this.fucData = function() {
        return this.age;
    }
}

const info = new fuc04('50','dave');
console.log(typeof dave);
console.log(info.age,info.name);

생성자 함수로 생성하는 방식으로, new() 를 사용하면 객체처럼 사용가능하지만 객체 리터럴 방식을 권장한다고 합니다. 참고용으로만 알아두세요!


prototype

자바스크립트에서 함수는 객체입니다. 객체는 프로퍼티 또는 메소드들을 추가적으로 가질 수 있고, 함수가 선언이 됨과 동시에 해당 함수는 객체가 되서 해당 객체는 기본적으로 "프로토 타입" 이라는 프로퍼티를 가지게됩니다. 그러므로 프로토 타입에다가 추가적으로 프로퍼티명을 넣음으로써 추가적인 프로퍼티나 메소드를 정의 (추가)할 수 있다고 합니다.

function fuc05(age,name){ // 선언과 동시에 객체생성
    this.age = age;
    this.name = name;
}

// 객체로 생성된 fuc05에 추가적인 메소드나 프로퍼티를 아래와같이 넣을 수 있다.
fuc05.prototype.message = function(){
    return 'Hello';
}

fuc05.prototype.hobby = 'coding';

const prototypeResult = new fuc05(10, 'dave');
console.log(prototypeResult.age,prototypeResult.name,prototypeResult.hobby);
console.log(prototypeResult.message); //메소드 호출

Class

class User01{
    constructor(name,age){ //클래스 생성자 함수 (function사용 X)
        this.name = name; // 클래스는 constructor 내부에서 this 키워드로 선언될 수 있음.
        this.age = age;
    }
    get_message(){
        return 'hello!';
    }
}
// class로 정의된 클래스는 new클래스명() 으로 객체로 생성될 수 있음.
const userDave = new User01('dave',20);
console.log(typeof userDave, userDave.name,userDave.age,userDave.get_message());

클래스 정의는 아래와 같이 할 수 있습니다.

class className{
  ...
}

또한, 클래스에서는 function 대신에 constructor 라는 클래스 생성자 함수를 사용합니다.
constructor 안에서 this로 선언될 수 있고, 객체 생성 시 인자 정의는 constructor 에서 할 수 있습니다.


class extends

class Animal{ //부모 클래스
    constructor(name){
        this.name = name;
    }
}

class User02 extends Animal{ //부모를 상속받은 자식 클래스
    constructor(name,age){
        super(name);
        this.age = age; //추가된 프로퍼티만 따로 this로 정의. 
    }
}

const result = new User02('Dave',30);
console.log(result.name,result.age);

클래스 상속을 할 때는 c언어나 JAVA와 같이 extends키워드를 사용합니다.


class Lion {
    constructor(name){
        this.name=name;
    }
    get_message(){
        return 'hi';
    }
}

class User03 extends Lion{
    constructor(name,age){
        super(name) //자식에서 부모 constructor 호출
        this.age=age;
    }
    //부모에서 정의한 함수를 자식에서는 다른 함수로 정의하고 싶을 때 부모 함수명을 그대로 쓰고, 실행 코드만 수정.
    get_message(){  
        return 'hihihihi';
    } 
}

const User03Result = new User03('dave',40);
console.log(User03Result.name,User03Result.age,User03Result.get_message());

자식에서 부모 클래스를 호출할 때에는 super 라는 키워드를 써줘야합니다. 괄호 안에는 부모 클래스가 가지고 있는 인자값을 그대로 써주면 되고, 자식에 인자값이 2개라면 this로 따로 선언을 해주면 됩니다. 만약에 부모 클래스에서 정의한 함수를 자식 클래스 한테는 다른 함수를 쓰고 싶다면? 위 코드처럼 부모 함수명을 그대로 쓰고, 실행 코드만 변경해주면 됩니다.


hasOwnProperty

class Mouse{
    constructor(name){
        this.name = name; //내부 프로퍼티
    }
    get_message(){
        return 'hello';
    }
}

Mouse.prototype.age = 10; //외부 프로퍼티

const User04 = new Mouse('dave');
console.log(User04.hasOwnProperty('name')); //true
console.log(User04.hasOwnProperty('age')); //false

내부에서 정의한 프로퍼티인지 외부에서 정의한 프로퍼티인지 true/false 를 통해 알 수 있습니다. 내부에서 정의된 것이면 true, 외부에서 정의된 것이면 false가 출력됩니다.
(프로퍼티가 아닌 메소드에는 사용되지 않습니다.)

0개의 댓글