본문 바로가기
패스트캠퍼스/수업내용정리

2019-05-13 프로토타입

by sunnykim91 2019. 5. 13.
const obj = {
  a: 1
};

console.log(Object.getOwnPropertyDescriptor(obj, 'a'));
// { value: 1, writable: true, enumerable: true, configurable: true }

console.log(obj.__proto__ === Object.prototype); // true
console.log(Object.getOwnPropertyDescriptor(obj, '__proto__')); // undefined
// getOwnPropertyDescriptor()
// 첫번째 인자로 준 객체에 프로퍼티 이름을 주면, 프로퍼티의 어트리뷰트를 반환

console.log(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'));

// {
//   get: [Function: get __proto__],
//     set: [Function: set __proto__],
//       enumerable: false,
//         configurable: true
// }

 

 

 

 

 

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

const me = new Person('Lee');
const you = new Person('Kim');

console.log(me.getName());
console.log(you.getName());

 

 

객체는 상태와 동작을 그룹화 한것.

 

 

__proto__는 접근자 프로퍼티이다.

__proto__ 접근자 프로퍼티를 코드 내에서 직접 사용하는 것은 비추천이다.

__proto__ 접근자 프로퍼티는 상속을 통해 사용된다.

__proto__ 접근자 프로퍼티를 통해 프로토타입에 접근하는 이유

 

 

Object.prototype에 접근을 하려면 __proto__ 나 get,set으로 접근 가능

 

 

캡슐화

const Person = (function () {
  // 생성자 함수
  function Person(name) {
    this.name = name;
  }

  // 프로토타입 메소드
  Person.prototype.sayHello = function () {
    console.log(`Hi! My name is ${this.name}`);
  };

  // 생성자 함수를 반환
  return Person;
}());

const me = new Person('Lee');

 

반응형