JaveScript/JaveScript

모던자바스크립트 26장 스터디

알면 알 수록 재밌다! 2023. 11. 26. 10:38

 

모던자바스크립트 스터디 12일차이다.

 

26장 ES6 함수의 추가기능

오늘은 위 단원을 공부하고 모르는것을 정리했다.

 


# 궁금증

  • 일반함수, 메서드, 화살표함수의 차이 정리

 

 

# 일반 함수

  • constructor: 주로 생성자 함수에서 객체를 초기화하는 데 사용
  • prototype: 객체 생성 시 메서드나 속성을 공유하기 위한 프로토타입 객체를 정의하는데 사용
  • super: 일반 함수는 사용 못함
  • arguments: 함수에 전달된 인자들의 리스트를 나타내는 객체
  • this: 함수가 호출될 때, 호출한 객체를 나타내는 키워드
# constructor
function Person(name, age) {
  this.name = name; // constructor
  this.age = age;
}

const john = new Person('jihoon', 28);

# prototype
function Dog(breed) {
  this.breed = breed;
}

Dog.prototype.bark = function() {
  console.log('Hi!'); // prototype
};

const goldenRetriever = new Dog('Golden Retriever');
goldenRetriever.bark();


# arguments
function sum() {
  let result = 0;
  for (let i = 0; i < arguments.length; i++) {
    result += arguments[i]; // arguments
  }
  return result;
}

console.log(sum(1, 2)); // 3

# this
function greet() {
  console.log('Hello, ' + this.name); // this
}

const person = { name: 'jihoon', greet: greet };
person.greet(); // Hello, jihoon

 

 


# 메서드

  • 메서드 내부에서는 super만 사용가능
  • super: 부모 클래스의 생성자를 호출하는 데 사용
  • 메서드에서 this는 메서드를 호출한 객체를 가리킴
  • 참고로 super는 클래스와 클래스의 인스턴스에서만 유효하므로 함수에서는 못씀
class Person {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    console.log("Who are U, I'm jihoon");
  }
}

class Student extends Person {
  constructor(name, parent) {
    super(name); // 부모 클래스의 생성자 호출
    this.parent = parent;
  }

  sayHi() {
    super.sayHi(); // 부모 클래스의 메서드 호출
    console.log("Hi, I'm Zzang Gu"); // 서브클래스에서 새로운 기능 추가
  }

  introduce() {
    console.log(`My parent name is ${this.parent} my name is ${this.name}`);
  }
}

const genericPerson = new Person("Personsssss");
genericPerson.sayHi(); // 출력: Who are U, I'm jihoon

const me = new Student("jihoon", "Fatherrrrr");
myDog.sayHi(); // 출력: Who are U, I'm jihoon \n Hi, I'm Zzang Gu
myDog.introduce(); // 출력: My parent name is jihoon my name is Fatherrrrr

# 화살표함수

  • constructor이나 prototype를 가지지 않음.
  • 화살표 함수는 생성자로 사용될 수 없으며, prototype을 사용하지 않음
  • super를 사용할 수 없음. 화살표 함수는 자신만의 this를 생성하지 않기 때문에 super가 필요하지 않음
  • arguments를 사용할 수 없음. 대신 화살표 함수 내에서 arguments 대신 Rest 파라미터(...args)를 사용
  • this는 화살표 함수가 정의된 문맥에서 상위 스코프의 this를 가져옴
const arrowFunction = (value) => {
  console.log(value); // this (lexical scoping), this 바인딩을 가지지 않음
};