Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 개발공부
- 끈기
- reactnative
- 데이터전송
- Linux
- 우선순위
- scope
- Andrew Ng
- 회고
- docker
- React
- Machine Learning
- Til
- javascript
- multer
- Sequence
- 스파르타코딩클럽
- coursera
- ES6
- 러닝자바스크립트
- 클로저
- 리눅스
- 자바스크립트
- 자료구조
- nodejs
- CSS
- 객체
- NextJS
- HTTP
- 1일1문장
Archives
- Today
- Total
해나아부지 개발일지
Object.create vs new #JavaScript 본문
Object.create(), new(생성자 함수) 모두 객체의 속성들을 상속받은 새로운 객체를 만들어 주는 것처럼 보인다.
Object.create
객체의 정의는 함수로부터 시작된다. 우리가 잘 아는 'object' ( { } ) 도 예외는 아니다.
함수가 정의될 때, constructor와 prototype도 함께 생성되는데 이것은 함수 내부의 접근을 도와주는 속성이다.
// Shape - 상위클래스
function Shape() {
this.x = 0;
this.y = 0;
}
개발자 콘솔에 Shape라는 class를 정의하고 prototype 속성을 보자!
constructor 에는 Shape 자신이 함수로 정의되어 있고 __proto__에는 'Object'에서 상속받은 여러가지 메서드(함수)들이 정의되어 있다.
const Rectangle.prototype = Object.create(Shape.prototype);
Rectangle에는 constructor가 존재하지 않기 때문에
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype의 constructor 속성을 Rectangle 자신을 생성한 함수로 지정을 해줘야만 한다.
class는 객체이기 때문에 prototype을 이용하면 속성 값에 접근할 수 있다. 속성의 추가나 메서드 함수를 추가해 줄 수 있다.
new(생성자 함수)
function Car(){
this.wheel = 18;
};
Car.prototype.cc = 2000;
//Using Object.create()
var audi = new Car();
var bmw = Object.create(Car.prototype);
console.log(bmw.wheel); //undefined
console.log(bmw.cc); //2000
//Using New Keyword
console.log(audi.wheel); //18
console.log(audi.cc); //2000
위의 예제를 보면 두 함수 사이의 차이점을 발견할 수 있다.
Object.create로 만든 bmw는 Car class의 this.wheel을 상속받지 못하고 new 로 만든 audi는 this.wheel을 상속 받았다.
결언
constructor가 실행 되느냐 안되느냐 의 차이가 있는 것 같다!
'Developers > OOP' 카테고리의 다른 글
ES6 Class 와 Super (0) | 2020.08.01 |
---|---|
객체 지향 프로그래밍(OOP: Object-Oriented-Programming)이란? (0) | 2020.07.30 |
Comments