메서드와 this, 화살표 함수

박선우·2022년 11월 9일
0

Javascript

목록 보기
2/3

메서드와 this

this 메서드를 호출한 객체

        let user = {
            name : "John",
            age : 30,
        }
        user.height = 199.9;    // 또는 user[height] = 199.9;
        user.say = function(){
            alert("Annyeonghaseo.");
        }   
        // 동적으로 프로퍼티 추가
        // say : 함수 포인터. 함수의 주소값을 say가 받음.
        let user = {
            name : "John",
            age : 30,
            say(){
                alert(this.name);      // == alert(user.name);
            }
        }
        let admin = user;
        user = null;
        user.say();
  • 자유로운 this
        let user = {name : "John"};
        let admin = {name : "Wick"};
        
		function say(){
            alert(this.name);
        }
        user.age = 25;
        user.func = say;
        admin.func = say;
        user.func();    // function say()의 this == user
        admin.func();   // function say()의 this == admin
		user['func']();
		admin['func']();
  • 화살표 함수 안에서의 this
    일반함수 안에 있는 일반함수의 this는 작동하지 못함.
        let user = {
            name : "Oliver",
            say(){
                function arrow(){
                    alert(this.name);
                }
                arrow();
            }
        };
		user.say();

화살표 함수 안에서의 this는 자신의 함수 상위에 있는 객체를 가리킨다.

        let user = {
            name : "Oliver",
            say(){
                let arrow = () => {
                    alert(this.name);
                }
                arrow();
            }
        };
        user.say();

객체 -> 메서드 & this -> 화살표 함수 -> 구조분해할당

profile
한 줄, 한 줄

0개의 댓글