'Javascript this'에 해당되는 글 1건

728x90

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수(self-reference variable)이다.

세부적인 사항은 https://velog.io/@realryankim/JavaScript-this%EB%9E%80 를 참조하면 도움된다.

 

// this
// 일반(normal) 함수는 호출 위치에 따라 this 정의
// 화살표(Arrow) 함수는 자신의 선언된 함수 범위에서 this 정의
 
const link2me = {
    name : 'Link2Me',
    normal: function () {
        console.log(this.name);
    },
    arrow: () => {
        console.log(this.name);
    }
}
 
link2me.normal(); // 결과 : Link2Me
link2me.arrow();  // 결과 : undefined
 
function User(name) {
    this.name = name;
}
 
User.prototype.normal = function () {
    console.log(this.name);
}
 
User.prototype.arrow = () => {
    console.log(this.name);
}
 
const link2u = new User('Link2U');
link2u.normal(); // 결과 : Link2U
link2u.arrow(); // 결과 : undefined

 

ES6 Class

- 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의미와는 다른 문법과 의미를 가진다.

- 자바스크립트에서 클래스 사용은 ES6에서부터 지원을 하기 시작했다. ES5까지 자바스크립트에는 클래스가 없었다.
  익스플로러에서는 해당 코드 사용이 불가능하나, 최신 브라우저를 이용할 경우 class를 지원한다.

  생김새만 클래스 구조이지, 엔진 내부적으로는 프로토타입 방식으로 작동된다.

- Class는 객체를 정의하기 위한 상태(멤버 변수)와 메서드(함수)로 구성된다.

 

클래스 내에서 정의한 메서드는 User.prototype에 저장한다.

class User {
    constructor(first, last) {
        this.firtstName = first;
        this.lastName = last;
    }
    getFullName(){
        return `${this.firtstName} ${this.lastName}`;
    }
}
 
const link2me = new User('Link2Me''Json');
link2me.getFullName();
 
console.log(link2me); // User { firtstName: 'Link2Me', lastName: 'Json' }
console.log(link2me.getFullName()); // Link2Me Json

new User('Link2Me', 'Json') 을 호출하면

1. 새로운 객체가 생성된다.

2. 넘겨받은 인수와 함께 constructor 가 자동으로 실행된다. 매개변수가 변수에 할당된다.

3. 객체의 메서드를 호출하면 메서드를 prototype 프로퍼티를 통해 가져온다.

    이 과정이 있기 때문에 객체에서 클래스 메서드에 접근할 수 있다.

 

클래스는 함수이다. alert(typeof User);

 

정확히는 생성자 메서드와 동일하다.
alert(User === User.prototype.constructor); // true

클래스 내부에서 정의한 메서드는 User.prototype에 저장된다.
alert(User.prototype.getFullName);

현재 프로토타입에는 메서드가 두 개다.
alert(Object.getOwnPropertyNames(User.prototype)); // constructor, getFullName

 

클래스 상속

// 클래스 구현 : 자바스크립트에서 클래스 사용은 ES6에서부터 지원
class Parent {
    sayHello() {
        return 'Hello world, from Parent Class';
    }
}
 
// 클래스 상속
class Child extends Parent {
}
 
const child = new Child();
console.log(child.sayHello());

 

 

 
class Person {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    console.log(`hello~ ${this.name}!`);
  }
 
  // 부모 클래스에서 클래스 필드로 메서드를 정의하면
  // 자식에서 super를 사용해서 호출할 수 없다.
  // 이 메서드는 프로토타입에 추가되는 것이 아니고, 객체에 추가된다.
  getRandom = () => {
    return Math.floor(Math.random() * 10);
  };
}
 
class Programmer extends Person {
  constructor(name, language) {
    super(name);
    this.language = language;
  }
  sayHello() {
    super.sayHello();
    console.log(`I like ${this.language}.`);
    console.log(`Your lucky number is ${super.getRandom()}`);
    // super는 프로토타입을 기반으로 동작한다.
    // super로 접근하려고 하면 에러가 발생한다. this 로 변경해보라.
  }
 
  // this로 자식에서도 찾고자 한다면 클래스 필드로 정의하면 된다.
  // getRandom = () =>
  getRandom() {
    return 20 + Math.floor(Math.random() * 10);
  }
}
 
const person1 = new Programmer('mike''javascript');
person1.sayHello();
 

 

 

 

class Person {
    age = 25;
    constructor(name) {
        this.name = name;
    }
    sayHello() { // this 인식
        console.log(`hello~ ${this.name}!`);
    }
 
    arrowName = () => {
        console.log(this.name);// this 인식
    };
 
    normalName = function(){
        console.log(this.name); // undefined
    }
}
 
class Programmer extends Person {
    constructor(name, language) {
        super(name);
        this.language = language;
    }
    sayHello() { // 메서드 오버라이딩
        super.sayHello();
        console.log(`${this.name}은 ${this.language} 언어를 좋아합니다.`);
    }
}
 
const p1 = new Person('강감찬');
p1.sayHello();
 
const p2 = new Programmer('홍길동''javascript');
p2.sayHello();
 
console.log(Person.prototype.age, Person.prototype.arrowName); // undefined undefined
console.log(Person.prototype.age, Person.prototype.normalName); // undefined undefined
 
const person1 = new Person('mike');
const person2 = new Person('jane');
person1.age = 50;
console.log(person1.age, person2.age); // 50 25
 
setTimeout(person1.arrowName, 100); // mike
setTimeout(person1.normalName, 100); // undefined
setTimeout(person2.arrowName, 100); // jane
setTimeout(person2.normalName, 100); // undefined
 

 

 

블로그 이미지

Link2Me

,