Imersive Prototype 이란?

미숙한 초보 코딩.Js·2019년 7월 29일
0

immersive

목록 보기
4/22
post-thumbnail

prototype

자바스크립트는 프로토타입 기반 언어라고 불립니다. 자바스크립트는 객체지향언어입니다. 그리고 class 라는 개념이 없어서 포로토타입으로 상속을 흉내내도록 합니다.
프로토 타입 기반 언어는 객체 원형인 프로토타입을 이용하여 새로운 객체를 만들어 냅니다.
이렇게 생성된 객체 역시 또 다른 객체의 원형이 될 수 있습니다.

	function Animal(type, name, sound) {
    	this.type = type;
        this.name = name;
        this.sound = sound;
    }
    
    Animal.prototype.say = function() {
    	console.log(this.sound); // 월월, 미야아옹
    };

	Animal.prototype.sharedValue = 1;
    
    const dog = new Animal('개', '멍멍이', '월월');
	const cat = new Animal('고양이', '야옹이', '미야아옹');

	dog.say();
	cat.say();
	console.log(dog.sharedValue); // 1
	console.log(cat.sharedValue); // 2

Animal 이라는 클래스를 만들어서 say, sharedValue들을 Animal에서 상속받아서 훨씬 유용하게 사용하도록 합니다..

ES6 Class

	class Animal{
    	constructor(type, name, sound){// 객체 생성자
        	this.type = type;
          	this.name = name;
          	this.sound = sound;
        }
      
      say() { // say 라는 함수를 class 내부에 생성 자동으로 프로토타입으로 설정됨, 메서드
      	console.log(this.sound);
      }
    }

	class Dog extends Animal{ // extends => 특정 클래스를 상속받는다.
    	constructor(name, sound) {
        	super('개', name, sound); // 자신이 상속받은 constructor 호출
        }
    }

	class Cat extends Animal{ // extends => 특정 클래스를 상속받는다.
    	constructor(name, sound) {
        	super('고양이', name, sound);
        }
    }

	console.log(Animal.prototype.say); // function say() {}
	
	const dog = new Dog('개', '멍멍이', '월월');
	const cat = new Cat('고양이', '야옹이', '미야오옹');

	dog.say();
	cat.say();
  • constructor는 class 안에 하나씩만 있어야 한다. 두개이상이면 SyntaxError발생합니다.
  • constructor는 인스턴스의 생성과 도시에 클래스 필드의 생성과 초기화를 실행합니다.
    따라서, 클래스 필드를 초기화 해야 한다면 constructor를 생략해서는 안됩니다.

super

  • 생성자 내부에서 super를 함수처럼 호출하면 부모 클래스의 생성자가 호출됩니다.
  • 정적 메소드 내부에서 super.prop과 같이 써서 부모 클래스의 prop 정적 속성에 접근할수있습니다.
  • 인스턴스 메소드 내부에서는 super.prop과 같이 써서 부모 클래스의 prop 인스턴스 속성에 접근할수있습니 다.
	class Person {
  		constructor({name, age}) {
    		this.name = name;
    		this.age = age;
  }
  	introduce() {
    	return `제 이름은 ${this.name} ${this.age}살입니다.`
  }
}

	class Student extends Person {
 		 constructor({grade, ...rest}) {
    		// 부모 클래스의 생성자를 호출할 수 있습니다.
    	super(rest);
    		this.grade = grade;
  }
  	introduce() {
    		// 부모 클래스의 `introduce` 메소드를 호출할 수 있습니다.
    	return super.introduce() + ` 저는 ${this.grade}학년입니다.`;
  }
}

const s = new Student({grade: 1, name: '스폰지밥', age: 26});
s.introduce(); // 제 이름은 스폰지밥 26살입니다. 저는 1학년입니다.
	

클래스 상속과 프로토타입 상속

class Person {}
class Student extends Person {};
class student = new Student;

Object.create()

부모의 기능을 복사한 새로운 객체를 생성한다.

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

const car1 = new Car('red');
const car2 = Object.create(Car.prototype);

// console.dir(car1); // Car { color: 'red' }
// console.dir(car2) // Car {}

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

const ToyCar = function() {
   
};

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

const legoCar = new ToyCar()
console.dir(legoCar) // 1번사진 처럼 나온다.
console.dir(legoCar instanceof ToyCar); 
console.dir(legoCar instanceof Car); // true 일까요 false 일까요? 
console.dir(legoCar instanceof Object); // true 일까요 false 일까요?

console.dir(ToyCar.prototype.isPrototypeof(legoCar); // ???

instance of

  • 조변수가 참조하고 있는 인스턴스의 실제 타입을 알아보기 위해 instanceof 연산자를 사용합니다.
  • 주로 조건문에 사용되며, instanceof의 왼쪽에는 참조변수를 오른쪽에는 타입(클래스명)이
    피연산자로 위치합니다. 그리고 연산의 결과로 boolean값인 true, false 중의 하나를 반환 합니다.
  • 쉽게 생각하면 객체를 생성한 생성자 함수,프로토타입 체인을 알 수 있다.

inPrototypeOf

  • 참쪼하꼬 잇는 프로토타이ㅃ 홖인

출처: https://arabiannight.tistory.com/entry/301 [아라비안나이트]
1번사진

profile
힘들땐 블로그 하나더 적자!!![ Suyang ]

0개의 댓글