프론트엔드/자바스크립트

Getter & Setter

테오구 2022. 3. 30. 21:15
728x90
class User {
	// 생성자 필드
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
		// get을 정의하는 순간 this.age는 메모리의 값이 아닌 get을 호출합니다.
		// get을 정의하는 순간 this.age는 메모리의 값이 아닌 get을 호출합니다.
  }

	// getter
  get age() {
    return this._age;
  }//값을 리턴

	// setter
  set age(value) {
    // 값을 설정할 수 있습니다.
		// 값을 받으면 그 값을 value로 설정
    // if (value < 0) {
    //   throw Error(`-1은 안됩니다..`);
    // }
    this._age = value < 0 ? 0 : value; // 생성자 필드명 앞에 _ 를 붙이는게 관습
  }
}
const user1 = new User(`Steve`, `job`, -10); // set
console.log(user1.age); // get
class User {
	// 생성자 필드
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
		// get을 정의하는 순간 this.age는 메모리의 값이 아닌 get을 호출합니다.
		// set을 정의하는 순간 age는 메모리의 값이 아닌 set을 호출합니다.
  }

	// getter
  get age() {
    return this._age;
  }//값을 리턴

	// setter
  set age(value) {
    // 값을 설정할 수 있습니다.
		// 값을 받으면 그 값을 value로 설정
    // if (value < 0) {
    //   throw Error(`-1은 안됩니다..`);
    // }
    this._age = value < 0 ? 0 : value; // 생성자 필드명 앞에 _ 를 붙이는게 관습
  }
}
const user1 = new User(`Steve`, `job`, -10); // set
console.log(user1.age); // get

<aside> 💡 사용자가 class를 잘못 사용해도 방어적인 자세로 만들수 있도록 해주는 것이 getter와 setter 이다.

</aside>

setter 실행 로직

getter 실행 로직

// getter와 setter의 이름을 접근자 프로퍼티 클래스의 상태처럼 보이기는
// 한데 실제로는 함수를 말하는 것
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  fullName() {
    return `${this.lastName} ${this.firstName}`
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName())
console.log(student.firstName)

학생의 firstName은 프로퍼티처럼 접근이 가능한데 fullName은 함수이기 때문에 호출하듯이 부르고 있습니다. 하지만 fullName은 이름이라는 상태를 얻는 것이기 때문에 함수처럼 호출하는게 조금은 어색할 수 있습니다. 이때 사용할 수 있는게 접근자 프로퍼티입니다.

// getter와 setter의 이름을 접근자 프로퍼티 클래스의 상태처럼 보이기는
// 한데 실제로는 함수를 말하는 것
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  get fullName() {
    return `${this.lastName} ${this.firstName}`
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName)
console.log(student.firstName)
// 접근자 프로퍼티를 쓰면 호출하는 시점에 데이터를 만들어서 리턴하는데
// 이건 속성에 가깝기 때문에 속성처럼 쓸 수 있습니다.
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  get fullName() {
    return `${this.lastName} ${this.firstName}`
  }
  set fullName(value) {
    console.log(value);
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName)
console.log(student.firstName)
// 접근자 프로퍼티를 쓰면 호출하는 시점에 데이터를 만들어서 리턴하는데
// 이건 속성에 가깝기 때문에 속성처럼 쓸 수 있습니다.
student.fullName = ''
// student의 fullName에 특정한 값을 할당한다면 set의 함수가 호출 됩니다.

class User { // 생성자 필드 constructor(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; // get을 정의하는 순간 this.age는 메모리의 값이 아닌 get을 호출합니다. // get을 정의하는 순간 this.age는 메모리의 값이 아닌 get을 호출합니다. } // getter get age() { return this._age; }//값을 리턴 // setter set age(value) { // 값을 설정할 수 있습니다. // 값을 받으면 그 값을 value로 설정 // if (value < 0) { // throw Error(`-1은 안됩니다..`); // } this._age = value < 0 ? 0 : value; // 생성자 필드명 앞에 _ 를 붙이는게 관습 } } const user1 = new User(`Steve`, `job`, -10); // set console.log(user1.age); // get

class User {
	// 생성자 필드
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
		// get을 정의하는 순간 this.age는 메모리의 값이 아닌 get을 호출합니다.
		// set을 정의하는 순간 age는 메모리의 값이 아닌 set을 호출합니다.
  }

	// getter
  get age() {
    return this._age;
  }//값을 리턴

	// setter
  set age(value) {
    // 값을 설정할 수 있습니다.
		// 값을 받으면 그 값을 value로 설정
    // if (value < 0) {
    //   throw Error(`-1은 안됩니다..`);
    // }
    this._age = value < 0 ? 0 : value; // 생성자 필드명 앞에 _ 를 붙이는게 관습
  }
}
const user1 = new User(`Steve`, `job`, -10); // set
console.log(user1.age); // get

<aside> 💡 사용자가 class를 잘못 사용해도 방어적인 자세로 만들수 있도록 해주는 것이 getter와 setter 이다.

</aside>

setter 실행 로직

getter 실행 로직

// getter와 setter의 이름을 접근자 프로퍼티 클래스의 상태처럼 보이기는
// 한데 실제로는 함수를 말하는 것
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  fullName() {
    return `${this.lastName} ${this.firstName}`
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName())
console.log(student.firstName)

학생의 firstName은 프로퍼티처럼 접근이 가능한데 fullName은 함수이기 때문에 호출하듯이 부르고 있습니다. 하지만 fullName은 이름이라는 상태를 얻는 것이기 때문에 함수처럼 호출하는게 조금은 어색할 수 있습니다. 이때 사용할 수 있는게 접근자 프로퍼티입니다.

// getter와 setter의 이름을 접근자 프로퍼티 클래스의 상태처럼 보이기는
// 한데 실제로는 함수를 말하는 것
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  get fullName() {
    return `${this.lastName} ${this.firstName}`
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName)
console.log(student.firstName)
// 접근자 프로퍼티를 쓰면 호출하는 시점에 데이터를 만들어서 리턴하는데
// 이건 속성에 가깝기 때문에 속성처럼 쓸 수 있습니다.
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  get fullName() {
    return `${this.lastName} ${this.firstName}`
  }
  set fullName(value) {
    console.log(value);
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName)
console.log(student.firstName)
// 접근자 프로퍼티를 쓰면 호출하는 시점에 데이터를 만들어서 리턴하는데
// 이건 속성에 가깝기 때문에 속성처럼 쓸 수 있습니다.
student.fullName = ''
// student의 fullName에 특정한 값을 할당한다면 set의 함수가 호출 됩니다.
class User {
	// 생성자 필드
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
		// get을 정의하는 순간 this.age는 메모리의 값이 아닌 get을 호출합니다.
		// set을 정의하는 순간 age는 메모리의 값이 아닌 set을 호출합니다.
  }

	// getter
  get age() {
    return this._age;
  }//값을 리턴

	// setter
  set age(value) {
    // 값을 설정할 수 있습니다.
		// 값을 받으면 그 값을 value로 설정
    // if (value < 0) {
    //   throw Error(`-1은 안됩니다..`);
    // }
    this._age = value < 0 ? 0 : value; // 생성자 필드명 앞에 _ 를 붙이는게 관습
  }
}
const user1 = new User(`Steve`, `job`, -10); // set
console.log(user1.age); // get

<aside> 💡 사용자가 class를 잘못 사용해도 방어적인 자세로 만들수 있도록 해주는 것이 getter와 setter 이다.

</aside>

setter 실행 로직

getter 실행 로직

// getter와 setter의 이름을 접근자 프로퍼티 클래스의 상태처럼 보이기는
// 한데 실제로는 함수를 말하는 것
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  fullName() {
    return `${this.lastName} ${this.firstName}`
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName())
console.log(student.firstName)

학생의 firstName은 프로퍼티처럼 접근이 가능한데 fullName은 함수이기 때문에 호출하듯이 부르고 있습니다. 하지만 fullName은 이름이라는 상태를 얻는 것이기 때문에 함수처럼 호출하는게 조금은 어색할 수 있습니다. 이때 사용할 수 있는게 접근자 프로퍼티입니다.

// getter와 setter의 이름을 접근자 프로퍼티 클래스의 상태처럼 보이기는
// 한데 실제로는 함수를 말하는 것
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  get fullName() {
    return `${this.lastName} ${this.firstName}`
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName)
console.log(student.firstName)
// 접근자 프로퍼티를 쓰면 호출하는 시점에 데이터를 만들어서 리턴하는데
// 이건 속성에 가깝기 때문에 속성처럼 쓸 수 있습니다.
class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName
    this.lastName = lastName
  }
  get fullName() {
    return `${this.lastName} ${this.firstName}`
  }
  set fullName(value) {
    console.log(value);
  }
}

const student = new Student('승빈', '홍')
console.log(student.fullName)
console.log(student.firstName)
// 접근자 프로퍼티를 쓰면 호출하는 시점에 데이터를 만들어서 리턴하는데
// 이건 속성에 가깝기 때문에 속성처럼 쓸 수 있습니다.
student.fullName = ''
// student의 fullName에 특정한 값을 할당한다면 set의 함수가 호출 됩니다.
728x90

'프론트엔드 > 자바스크립트' 카테고리의 다른 글

이터러블  (0) 2022.04.04
Inheritance  (0) 2022.03.31
논리 연산자  (0) 2021.10.15
foreach, for in, for of  (0) 2021.10.09
클래스와 인스턴스  (0) 2021.10.05