Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[16, 17장] 프로퍼티 어트리뷰트, 생성자 함수에 의한 객체 생성 #10

Open
juyeon-park opened this issue Jun 15, 2023 · 6 comments
Assignees

Comments

@juyeon-park
Copy link
Member

데브코스 4기 프롱이들 모던 JS Deep Dive 책 뿌수기😎

아래 템플릿을 복사해서 2개이상 퀴즈를 만들어주세요. 객관식, 주관식, 단답형 모두 상관없습니다!

Q. 퀴즈 내용
1.  1번
2.  2번
3.  3번

<details>
<summary>퀴즈 정답</summary>
<div markdown="1">    
정답 설명
</div>
</details>
@ghost
Copy link

ghost commented Jun 19, 2023

Q. 프로퍼티 어트리뷰트 , 생성자 함수

  1. 다음 설명을 보시고 어떤 용어의 설명인지 맞춰보세요!
(1) 키와 값으로 구성된 일반적인 프로퍼티
(2) 자체적으로 값을 갖지는 않으나 프로퍼티의 값을 읽거나 저장할때 호출되는 함수로 구성된 프로퍼티
(3) [[Value]], [[Writable]], [[Enumerable]], [[Configurable]]  같은 의사 프로퍼티를 통칭하는 용어 (4글자)
(4) [[Get]], [[Set]]  같은 의사 메서드를 통칭하는 용어 
(5) (3), (4) 모두 포함하는 용어 (프로퍼티 디스크립터 객체가 제공한다.)
  1. 다음 빈칸의 A, B, C, D, E 가 무엇인지 맞춰보세요!
내부 메서드 [[Call]] 갖는 함수 객체를 callable 라고 하며, 
내부 메서드 (E) 갖는 함수 객체를 (A), (E) 갖지 않는 함수 객체를 (B)라고 부른다.

결론적으로 함수객체는 callable 이면서 (A)이거나 callable 이면서 (B)이다. , 모든 함수 객체를 생성자 함수로서
호출할  있는 것은 아니다.

new 연산자와 함께 호출되는 함수는 (B) 아닌 (A)이어야만 한다.

(A) 함수 선언문, 함수 표현식, (C) 같은 방식으로 정의된 함수를 말하며
(B) 메서드(ES6 메서드 축약 표현) , (D) 같은 방식으로 정의된 함수를 말한다.
  1. 함수가 new 연산자를 써서 호출됐는지, new 연산자를 쓰지 않고 호출됐는지 판단하는 연산자는?

  2. 어떤 객체의 프로퍼티가 for...in문이나 Object.keys로 열거될 수 있는가를 나타내는 내부 슬롯은?

퀴즈 정답 (미리 보진 말아주세요 ㅜ_ㅜ)
정답 설명
1. (1) 데이터 프로퍼티, (2) 접근자 프로퍼티, (3) 내부 슬롯, (4) 내부 메서드, (5) 프로퍼티 어트리뷰트
2. (A) constructor, (B) non-constructor, (C) 클래스, (D) 화살표 함수, (E) [[Construct]]
3. new.target
4. [[Enumerable]]

@eeseung
Copy link
Collaborator

eeseung commented Jun 20, 2023

Q. 아래 코드의 실행 결과를 예상해 보세요.

const study = {};

Object.defineProperties(study, {
  index: {
    value: '16장'
  },
  title: {
    value: '프로퍼티 어트리뷰트',
    writable: true,
    enumerable: true,
    configurable: true,
  },
  chapter: {
    get() {
      return `${this.index}.${this.title}`;
    },
    set(string) {
      [this.index, this.title] = string.split('.');
    },
    enumerable: true,
    configurable: true,
  }
});

study.chapter = '17장.생성자 함수에 의한 객체 생성';
console.log(study.chapter);
console.log(Object.keys(study));
퀴즈 정답
16장.생성자 함수에 의한 객체 생성
['title', 'chapter']

Q. 프롱이가 생성자 함수의 인스턴스 생성 과정에 대해 주석을 달아 설명하려고 합니다. <보기>에서 알맞은 것을 골라 주석을 완성하세요.

function Circle(radius) {
  // (1)

  // (2)
  this.radius = radius;
  this.getDiameter = function () {
    return 2 * this.radius;
  }

  // (3) 
  return 100;
}

const circle = new Circle(1);
console.log(circle);

<보기>
A. 암묵적으로 this를 반환한다.
B. 암묵적으로 빈 객체가 생성되고 this에 바인딩된다.
C. 명시적으로 원시 값을 반환한다.
D. this에 바인딩되어 있는 인스턴스를 초기화한다.
E. 암묵적인 this 반환이 무시된다.

퀴즈 정답
(1) B (2) D (3) A

@juyeon-park
Copy link
Member Author

juyeon-park commented Jun 20, 2023

Q1. 다음 코드의 실행결과를 작성해주세요

const person = { lastName: 'Hong' };
Object.seal(person);

person.age = 26; 
console.log(person);     // (1)

delete person.lastName; 
console.log(person);     // (2)

person.lastName= 'Park';
console.log(person);     // (3)

Object.defineProperty(person, "lastName", {configurable: true});   // (4)

(1)
(2)
(3)
(4)

퀴즈 정답
Object.seal메소드는 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 금지를 의미한다!! 밀봉된 객체는 읽기와 쓰기만 가능하다

(1) { lastName: 'Hong' }
설명 : 프로퍼티 추가 금지
(2) { lastName: 'Hong' }
설명 : 프로퍼티 삭제 금지
(3) { lastName: 'Park' }
설명 : 프로퍼티 값 갱신은 가능
(4) TypeError : Cannot redefine property : lastName
설명 : 프로퍼티 어트리뷰트 재정의 금지

Q2. 다음 코드의 실행결과를 작성해주세요

const func1 = function( ) { 
   console.log('프롱이들');
};

const func2 = ( ) => {
    console.log('프롱이들');
 };

new func1();   // (1) 실행시 나타나는 출력 결과는?
new func2();   // (2) 실행시 나타나는 출력 결과는?

(1)
(2)

퀴즈 정답
(1) 프롱이들
설명 : 함수 표현식으로 정의된 함수는 constructor

(2) TypeError : func2 is not a constructor
설명 : 화살표 함수로 정의된 함수는 non-constructor

※ constructor = 생성자 함수로서 호출할 수 있는 함수
※ non-constructor = 객체를 생성자 함수로서 호출할 수 없는 함수

@suehdn suehdn changed the title [16, 17장] 프로퍼티 어트리뷰트, 생정자 함수에 의한 객체 생성 [16, 17장] 프로퍼티 어트리뷰트, 생성자 함수에 의한 객체 생성 Jun 21, 2023
@hyoribogo
Copy link
Member

hyoribogo commented Jun 21, 2023

Q. 다음 코드의 실행 결과를 작성해 주세요.

const person = { name: 'Frong' }
Object.freeze(person)

person.name = 'Hyori'
console.log(person)
퀴즈 정답

image

그대로 {name: 'Frong'} 가 반환됩니다.
특히, person.name = 'Hyori' 부분에서 strict mode가 아닐 땐 에러가 나지 않지만, strict mode일 때는 에러가 나게 됩니다.



Q. 다음 코드에 알맞은 답을 해주세요.

const person = {}

Object.defineProperty(person, 'age', {
    value: 25,
    writable: true,
    enumerable: true,
    configurable: false
})
// 1. 해당 코드를 특정 메서드를 사용해 더 간결하게 작성할 수 있습니다. 어떻게 작성할 수 있을까요?

delete person.age
console.log(person.age)
// 2. delete를 이용해 age 프로퍼티를 삭제하면 무슨 결과가 나타날까요?
퀴즈 정답

1. Object.seal() 메서드 활용
image
해당 메서드를 활용하면, configurable 값만 false로 생성되는 것을 확인할 수 있습니다.
image


2. configurable 값이 false이기 때문에, age 프로퍼티는 삭제되지 않습니다.
따라서 person.age를 출력하면 기존의 25 값이 나오는 것을 알 수 있습니다.
image

@jonghyunlee95
Copy link
Collaborator

jonghyunlee95 commented Jun 21, 2023

Q. [[Prototype]]내부 슬롯을 간접적으로 접근 할 수 있게 해주는 키워드는?

퀴즈 정답 정답: __proto__
const o = {};

// 내부 슬롯은 자바스크립트 엔진의 내부 로직이므로 직접 접근할 수 없다.
o.[[Prototype]] // Uncaught SyntaxError: Unexpected token '['

// 일부 내부 슬롯과 내부 매서드에 한하여 간접적으로 접근할 수 있는 수단을 제공
o.__proto__ // Object.prototype

Q. Object.seal메서드와 Object.freeze메서드의 가장 큰 차이점은?

퀴즈 정답 정답: seal 메서드는 프로퍼티 값의 갱신이 가능하지만 freeze메서드는 프로퍼티 값의 갱신이 불가능하다.
const frong = { language: "JS" }
// 객체 frong을 seal 메서드를 이용하여 밀봉
Object.seal(frong);
// seal메서드를 이용해 객체를 밀봉했을때는 
// 추가, 삭제, 재정의는 불가능하지만 프로퍼티 값의 갱신은 가능!
frong.language = "Javascript"; 
console.log(frong); // { language: "Javascript" }

const frong = { language: "JS" }
// 객체 frong을 freeze 메서드를 이용하여 동결
Object.freeze(frong);
// freeze메서드를 이용해 객체를 동결했을때는 
// 추가, 삭제, 재정의 불가능, 프로퍼티 값의 갱신 역시 불가능!
frong.language = "Javascript" // 무시, strict mode에서는 에러발생
console.log(frong); // { language: "JS" }

Q. 다음 코드의 실행결과를 작성해주세요.

function DevCorse(position) {
  this.position = position;
  this.printPosition = () => {
    return `we are ${this.position}!`
  }
}

const devCorse = DevCorse('frong');
console.log(devCorse.printPosition());
퀴즈 정답

정답: 생성자 함수를 호출할때는 앞에 new연산자를 붙여서 실행하지않으면
함수의 반환문이 없어서 undefined가 상수devCorse에 할당되고 undefined의 printPosition은 존재하지 않기에 에러가 발생합니다.

스크린샷 2023-06-21 오후 3 40 58

스크린샷 2023-06-21 오후 3 28 05

new연산자를 사용하여 상수 devCorse에 생성자 함수 DevCorse가 할당되었고
생성자 함수 DevCorse에 파라미터로 받은 문자열"frong"이 this.position으로 할당되어 정상 작동합니다.

스크린샷 2023-06-21 오후 3 44 13

스크린샷 2023-06-21 오후 3 25 38

TMI

생성자함수에 return문을 넣은 뒤 new를 붙이지않고 사용하면 어떻게 될까 궁금해서 한번 해봤는데 일반 함수처럼 return이 되네요!

스크린샷 2023-06-21 오후 3 59 39

@dudwns
Copy link
Member

dudwns commented Jun 21, 2023

Q1. 다음 코드를 실행했을 때 결과를 올바르게 나열한 것은? (객관식)

const animal = { name: "nana" };

Object.freeze(animal);

console.log(Object.getOwnPropertyDescriptors(animal));
// {value: "nana", writable: ?, enumerable: ?, configurable: ?}

(1). true, false, true
(2). false, true, false
(3). true, false, false
(4). false, true, true
(5). false, false, false

Q2. 다음 코드의 출력 결과는? (객관식)

function Cat(name, age) {
  this.name = name;
  this.age = age;
  this.introduce = function () {
    return `이름은 ${name}, 나이는 ${age} 입니다. `;
  };
  return [name];
}

function Dog(name, age) {
  this.name = name;
  this.age = age;
  this.introduce = function () {
    return `이름은 ${name}, 나이는 ${age} 입니다. `;
  };
  return age;
}

const cat = new Cat("coco", 3);
const dog = new Dog("choco", 5);
console.log(cat); // (가)
console.log(dog); // (나)

     (가)                                                                                        (나)

(1). undefined                                                                             5

(2). ['coco']                                                                                  undefined

(3). Cat { name: 'coco', age: 3, introduce: f }                               Dog { name: 'choco', age: 5, introduce: f }

(4). ['coco']                                                                                  Dog { name: 'choco', age: 5, introduce: f }

(5). Cat { name: 'coco', age: 3, introduce: f }                               5

퀴즈 정답

1번 문제
Object.freeze 메서드는 객체를 동결한다.

객체 동결이란 프로퍼티 추가 및 삭제와 프로퍼티 어트리뷰트 재정의 금지, 프로퍼티 값 갱신 금지를 의미한다.

따라서 값의 변경 가능 여부를 나타내는 Writable과 재정의 가능 여부를 나타내는 Configurable은 false가 되고, 열거 가능 여부를 나타내는 Enumerable은 동결과는 관계가 없기 때문에 true를 나타낸다.

정답: (2)

2번 문제
(가): 생성자 함수에서 this가 아닌 다른 객체를 명시적으로 반환하면 this가 반환되지 못하고 return 문에 명시한 객체가 반환된다.
(나): 참조 값이 아닌 원시 값을 명시적으로 반환하면 원시 값 반환은 무시되고 암묵적으로 this가 반환된다.

정답: (4)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants