javascript 에서 OOP 흉내내기 (심화1)

김주빈·2020년 3월 25일
0

JS 개념

목록 보기
2/2
post-thumbnail

prototype 이란 무엇일까?

function Humen(name) {
  this.name = name;
}
Humen.prototype.sleep = function() {
  console.log("zzzzzz");
}

var steve = new Humen("steve")

prototype

prototype 은 OOP 가 아닌 javascript 에서 OOP 의 개념을 흉내내기 위해 나온 특성이며, 상속을 하는 객체에서 가지고 있는 특성 이라고 생각하면 된다.
상속을 받는 객체에서도 prototype 에 접근이 가능하며,
위의 코드에서 steve 은 상속 받는 객체이며 Humen 은 상속을 하는 객체이다.
다른 말로는 steveConstructorHumen 이며,
HumenconstructorObject 이다.

__proto__

위의 이미지는 오승환님 블로그 프로토타입 이해하기 에서 가지고 왔다.

protoconstructorprototype 을 가르킨다.

steve.__proto__ === Humen.prototype;			//true
steve.__proto__ === steve.constructor.prototype;	//true

Object.create

object.create()prototype 을 deep copy 하여 다른 constructor 에 할당함으로써 다른 constructor 가 prototype 을 변경하더라도 원본 prototype 이 변하지 않게 하는 method이다.

var Car = function(name) {
  this.name = name;
  console.log(`${this.name} is car`);
}
Car.prototype.stop = function() {
  console.log(`${this.name} is stop`);
}

var Humen = function(name) {
  this.name = name;
  console.log(`${this.name} is Humen`);
}
Humen.prototype = Car.prototype;
Humen.prototype.stop = function(){
  console.log(`${this.name} is never stop`);
}

var avante = new Car('avante');
console.log(avante.stop())  // avante is never stop
// Humen 의 prototype 을 변경햇지만 shallow copy 가 된 
// Car 의 prototype 도 같이 변경이 되었다.

Humenprototype 을 변경하면 원본인 Car 의 형태값도 같이 바뀐다. 그걸 방지하기 위해 create method를 사용하는데

var Car = function(name) {
  this.name = name;
  console.log(this.name + ' ' + 'running');
};
Car.prototype.stop = function() {
  console.log(this.name + ' ' + 'Stop!!');
};
var Humen = function() {
  Car.apply(this, arguments);	//this 값을 바인딩 해줘야 한다.
  console.log(this.name + ' ' + 'Eatting');
};
Humen.prototype = Object.create(Car.prototype);   
// Humen 의 prototype 을 Car 의 Prototype 의 값으로 할당; (Deep copy);

Humen.prototype.stop = function() {
  console.log(`${this.name} is never stop`);
}
var avante = new Car('avante'); // avante running
console.log(avante.stop());     // avnate Stop!!
var runner = new Humen('Kim');  // Kim runnig 
                                // Kim Eatting
console.log(runner.stop());     // Kim never stop!!
//deep copy 가 되어 Humen, Car 독립적은 Prototype 을 가지게 되었다.

그러나 여전히 Humen 의 prototype 의 constructor 는 Car 를 가르키게 되어

Humen.prototype.constructor = Humen
profile
프론트엔드 개발자 김 주빈 입니다.

0개의 댓글