본문 바로가기

코드스테이츠(Immersive)/체크포인트

Checkpoints 04 - JS Prototypes(Object.create)

// Object.create(prototypeObject, propertyObject);

const myObject = Object.create(Object.prototype);
const myLiteral = {};
const noProto = Object.create(null); // no properties

const Car = function(color){
	this.color = color;
}

const car1 = new Car('red'); // using constructor
const car2 = Object.create(Car); // no constructor

Car.prototype = {
	getColor(){
    	return this.color;
        }
}

const ToyCar = function(){
	
}

ToyCar.prototype = Object.create(Car.prototype);

const legoCar = new ToyCar();
console.dir(legoCar instanceof ToyCar); // true
console.dir(Car.prototype.isPrototypeOf(legoCar)); // true
console.dir(legoCar instanceof Object); // true

 

1.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);

var result = obj2.x;

 

2.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);

obj2.x = 20;

var result = obj2.x;

obj1.x 를 참조한 값을 바꿔주는게 아니라 obj2.x를 새로 설정

 

3.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);

obj2.x = 20;

var result = obj1.x;

obj.1의 x는 변화가 생기지 않음

 

4.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);

obj1.x = obj1.x + 20;

var result = obj1.x;

 

5.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);
var obj3 = Object.create(obj1);

obj1.x = 15;

var result = obj2.x + obj3.x;

obj2, obj3의 x가 없기때문에 obj1의 x를 참조(복사가 아님)

 

6.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);

obj2.x += 10; //  obj2.x = obj2.x + 10;
obj1.x = 15;

var result = obj2.x;

 

7.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);
var obj3 = Object.create(obj2);

var result = obj3.x + 10;

프로토타입 체인을 통해 obj2 > obj1

 

8.

var obj1 = { x: 10 };
var obj2 = Object.create(obj1);
var obj3 = Object.create(obj2);

obj2.x = 20;

var result = obj3.x + 10;

 

9.

var MyFunc = function () {};
MyFunc.prototype.x = 10; // new 키워드로 인스턴스가 만들어질때, 새로 만들어지는 인스턴스의 __proto__에 들어갈 객체
var obj1 = new MyFunc();
var obj2 = new MyFunc();

var result = obj1.x + 10;

// funfunfunction prototype 참고

prototype 함수에만 생긴다