19.12 정적 프로퍼티/메서드

정적 프로퍼티/메서드: 생성자 함수로 인스턴스를 생성하지 않아도 참조/호출할 수 있는 프로퍼티/메서드를 말한다. ( ⇒ 인스턴스에서 참조/호출이 불가능한 프로퍼티/메서드라고도 말할 수 있음)

function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function () {
  console.log(`Hi! I'm ${this.name}`);
};

Person.staticProp = '정적 프로퍼티입니다.';

Person.staticMethod = function () {
  console.log('정적 메서드입니다.');
};

const person1 = new Person('Lisa');

person1.sayHello(); // Hi! I'm Lisa.
//person1.staticMethod(); // Error
console.log(person1.staticProp); // undefined

Person.staticMethod(); // 정적 메서드입니다.
console.log(Person.staticProp); // 정적 프로퍼티입니다.

Object.create = 정적 메서드 ???????

// Object.create = 정적 메서드
const obj = Object.create({ name: 'Lee' });
console.log(obj); // {}

//  Object.prototype.hasOwnProperty = 프로토타입 메서드
console.log(obj.hasOwnProperty('name')); // false

19.13 프로퍼티 존재 확인

<aside> ✍️ 객체 내에 특정 프로퍼티가 존재하는지 확인할 수 있는 방법에 대해 살펴보자!

</aside>

in 연산자

const person = {
  name: 'Lee',
  address: 'Seoul',
};

console.log('name' in person); // true
console.log('address' in person); // true
console.log('age' in person); // false

// 왜???!😱
console.log('toString' in person); // true

ES6에서 도입된 Reflect.has 메서드를 사용해도 in 연산자와 똑같이 동작한다.

const person = {
  name: 'Lee',
  address: 'Seoul',
};

console.log(Reflect.has(person, 'name')); // true
console.log(Reflect.has(person, 'address')); // true
console.log(Reflect.has(person, 'age')); // false

// toString도 똑같이 true로 출력이 됨 😱
console.log(Reflect.has(person, 'toString')); // true

Object.prototype.hasOwnProperty 메서드

→ 이름에서 알 수 있듯이 객체 자신에 해당 프로퍼티가 있는지 확인할 수 있는 메서드