라이브러리

[JAVASCRIPT] Object.create(proto) - 지정된 프로토타입을 가진 새 객체 생성




Object.create(proto)란 무엇인가?

JavaScript의 Object.create() 메서드는 지정된 프로토 타입을 사용하여 새로운 객체를 생성합니다. 이 메서드는 Object.prototype.create() 메서드의 이름을 사용하지만, Object.prototype.create() 메서드는 새로 추가된 메서드입니다.

Object.create(proto)의 인수

Object.create() 메서드는 두 개의 인수를 받을 수 있습니다.

- proto: 프로토 타입을 지정합니다. 프로토 타입은 객체의 상위 객체로, 객체가 상속받는 속성과 메서드를 정의합니다.
- properties: 옵션 인수입니다. 프로퍼티를 지정하여 객체에 추가할 수 있습니다.

Object.create(proto)의 예제

#hostingforum.kr
javascript

// 프로토 타입을 지정하여 새로운 객체를 생성합니다.

const personProto = {

  name: 'John',

  age: 30,

  sayHello: function() {

    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);

  }

};



const person = Object.create(personProto);

console.log(person.name); // John

console.log(person.age); // 30

person.sayHello(); // Hello, my name is John and I'm 30 years old.



// 프로퍼티를 지정하여 객체에 추가합니다.

const person2 = Object.create(personProto, {

  name: { value: 'Jane', writable: true },

  age: { value: 25, writable: true }

});

console.log(person2.name); // Jane

console.log(person2.age); // 25

person2.sayHello(); // Hello, my name is Jane and I'm 25 years old.



Object.create(proto)의 장점

- 상속: 프로토 타입을 사용하여 객체의 상속을 쉽게 구현할 수 있습니다.
- 재사용: 프로토 타입을 재사용하여 객체를 생성할 수 있습니다.
- flexible: 프로퍼티를 지정하여 객체에 추가할 수 있습니다.

Object.create(proto)의 단점

- 복잡: 프로토 타입을 사용하여 객체의 상속을 구현할 때 복잡성이 증가할 수 있습니다.
- 오류: 프로토 타입을 사용하여 객체의 상속을 구현할 때 오류가 발생할 수 있습니다.

Object.create(proto)의 결론

Object.create(proto) 메서드는 JavaScript의 객체 생성을 위한 유용한 도구입니다. 프로토 타입을 사용하여 객체의 상속을 쉽게 구현할 수 있으며, 프로퍼티를 지정하여 객체에 추가할 수 있습니다. 그러나 복잡성과 오류가 발생할 수 있으므로 주의하여 사용해야 합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 177건 / 11 페이지

검색

게시물 검색