반응형
Prototype(프로토타입)
- 함수는 생성될때 기본적으로 프로토타입이 만들어짐
- 각 함수의 객체마다 변수가 생성되지 않고 공통적으로 쓰는 값이 필요할때 쓰임
- 함수(==클래스) 고유의 전역변수, 전역함수 라고 보면 됨
함수선언, 객체당 변수가 각각 생성되는 형태
//함수선언(== 클래스선언) function Person() { this.eyes = 2; this.nose = 1; } //객체당 변수가 각각 생성 var kim = new Person(); var park = new Person(); console.log(kim.eyes); // => 2 console.log(kim.nose); // => 1 console.log(park.eyes); // => 2 console.log(park.nose); // => 1
프로토타입 사용
//함수선언 function Person() {} //각 함수는 생성과 동시에 prototype이 만들어짐 Person.prototype.eyes = 2; Person.prototype.nose = 1; //객체당 변수 만들어지지 않음! var kim = new Person(); var park = new Person(): console.log(kim.eyes); // => 2
Object객체 안의 기본 프로토타입(toString())
//Object객체 생성 var obj = {}; var obj = new Object(); //Person은 Object에서 상속받은 객체라고 생각하면 됨 function Person() {} // => 함수 var personObject = new Person(); // => 함수로 객체를 생성 //Prototype Link, Object function Person() {} //Prototype Link : Person에 포함된 Object의 toString()실행 console.log(Person.prototype.toString()); // "[object Object]" //Object의 toString() 프로토타입 재정의 Person.prototype.toString = function() { return 'myToString' } //Prototype Object : Person의 prototype에 재정의한 toString()실행 console.log(Person.prototype.toString(); // "myToString"
반응형
'웹 > javascript' 카테고리의 다른 글
Javascript 싱글톤 패턴 모듈, 모듈+네임스페이스 패턴 2개 (0) | 2021.11.18 |
---|---|
Javascript 객체 정의 방법, 클로져 IIES 패턴 모듈, 클로져 생성자 패턴 모듈 (0) | 2021.11.18 |
Javascript 즉시실행함수(IIFE), 클로져(Closure) (0) | 2021.11.18 |
Javascript Math, alert, confirm, prompt (0) | 2021.11.18 |
Javascript Array, String(배열, 문자열) 다루기 (0) | 2021.11.18 |
최근댓글