프로토타입 #7
Replies: 5 comments
-
프로토타입자바스크립트는 프로토타입 기반 언어입니다. 클래스 기반 언어에서는 ‘상속’을 사용하지만 프로토타입 기반 언어에서는 어떤 객체를 원형으로 삼고 이를 복제(참조) 함으로써 상속과 비슷한 효과를 얻습니다. 6-1 프로토타입 개념 이해constructor, prototype, instance위 그림만 이해하면 프로토타입은 끝입니다(?) 이 그림으로부터 전체 구조를 파악할 수 있고, 반대로 전체 구조로부터 이 그림을 도출해낼 수 있으면 됩니다.var instance = new Constructor();이를 바탕으로 좀 더 구체적인 형태로 바꾸면 다음과 같습니다. 위의 실선의 왼쪽 꼭짓점에는
예를 들어 var Person = function(name){
this._name = name;
};
Person.prototype.getName = function(){
return this._name;
}이제 왜냐하면 var suzi = new Person('Suzi');
suzi.__proto__.getName(); // undefined
Person.prototype === suzi.__proto__메서드 호출 결과로 우리는 앞선 배움으로부터 어떤 함수를 ‘메서드로서’ 호출할 때는 메서드명 바로 앞의 객체가 곧 this가 된다고 했습니다. 그러니까 그럼 만약 var suzi = new Person('Suzi');
suzi.__proto__._name = 'SUZI__proto__';
suzi.__proto__.getName(); // SUZI__proto__예상대로 SUZI__proto__가 잘 출력됩니다. 그러니까 관건은 this입니다. this를 인스턴스로 할 수 있다면 좋겠습니다. 그 방법은 var suzi = new Person('Suzi',28);
suzi.getName();
var iu = new Person('Jieun',28);
iu.getName();
그 이유는 바로
“ 여기까지 이해했다면 프로토타입을 이해한 것이나 마찬가지입니다! 더 자세한 설명
var Constructor = function(name){
this.name = name;
};
Constructor.prototype.method1 = function(){};
Constructor.prototype.property1 = 'Constructor Prototype Proterty';
var instance = new Constructor('Instance');
console.dir(Constructor);
console.dir(instance);
대표적인 내장 생성자 함수인 var arr = [1,2];
console.dir(arr);
console.dir(Array);왼쪽은 arr 변수를 출력한 결과이고, 오른쪽은 생성자 함수인 Array를 출력한 결과이다. arr 변수 출력한 결과(왼쪽)
생성자 함수인 Array 출력 결과(오른쪽)
이를 바탕으로 도식을 구체화하면 다음과 같습니다.
한편 |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
메서드 오버라이드, 프로토타입 체인인스턴스가 생성될 때, 생략 가능한 프로퍼티인 Prototype Object
위의 그림과 같이 Prototype Object는 세가지 영역으로 구성된다.
Prototype Link
function Human(name) {
this.name = name;
}
// 생성자 함수의 prototype 프로퍼티를 통해서 메소드를 추가하였다.
Human.prototype.printName = function () {
console.log(this.name);
}
const chanwoo = new Human('chanwoo');위의 코드를 통해 인스턴스를 생성하게 되면 아래의 구조와 같이 객체가 생성된다.
인스턴스는 Prototype Link를 통해 Prototype Object를 접근할 수 있고, 이는 Prototype Chain
Prototype을 통해 상속받는 프로퍼티와 메소드를 사용하기 위해 참조하는 방식은 아래와 같다.
이전 예제를 통해 Prototype Chain의 동작 방식을 설명하고자 한다. function Human(name) {
this.name = name;
}
// 생성자 함수의 prototype 프로퍼티를 통해서 메소드를 추가하였다.
Human.prototype.printName = function () {
console.log(this.name);
}
const chanwoo = new Human('chanwoo');
chanwoo.printName(); // ----- A
chanwoo.hasOwnProperty('name'); // ----- B1) A,
|
Beta Was this translation helpful? Give feedback.
-
6-2-3 객체 전용 메서드의 예외사항어떤 생성자 함수이든 prototype은 반드시 객체이기 때문에 때문에 객체에서만 사용할 메서드는 다른 데이터 타입처럼 프로토타입 객체 안에 정의할 수 없다. 객체에서만 사용할 메서드를 Object.prototype.getEntries = function() {
var res = [];
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
res.push([prop, this[prop]]);
}
}
return res;
};
// getEntries는 모든 데이터 타입에 대해 사용가능한 메서드가 되어버림
var data = [
['object', { a: 1, b: 2, c: 3 }], // [["a",1], ["b", 2], ["c",3]]
['number', 345], // []
['string', 'abc'], // [["0","a"], ["1","b"], ["2","c"]]
['boolean', false], // []
['func', function () {}], // []
['array', [1, 2, 3]] // [["0", 1], ["1", 2], ["2", 3]]
];
data.forEach(function (datum) {
console.log(datum[1].getEntries());
});이를 해결하는 방법은 Object에 static method로 객체 전용 메서드를 생성하는 방법이 있다. 다만 이렇게 되면 객체 전용메서드를 예를 들어 그렇기 때문에
6-2-4 다중 프로토타입 체인자바스크립트의 기본 데이터 타입들은 모두 프로토타입 체인이 1단계, 2단계로 끝나게 되지만, 사용자가 새롭게 만드는 경우는 그 이상도 가능하다.
var Grade = function () {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < args.length; i++) {
this[i] = args[i];
}
this.length = args.length;
};
var g = new Grade(100, 80); // 변수 g는 Grade의 인스턴스를 바라보며, 유사배열객체이다.
// Grade 프로토타입이 배열의 인스턴스를 바라보게 하면, 배열 메서드를 사용할 수 있다.
Grade.prototype = [];
console.log(g); // Grade(2) [100, 80]
g.pop();
console.log(g); // Grade(1) [100]
g.push(90);
console.log(g); // Grade(2) [100, 90] |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.














Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
이번주 주제는 '프로토타입' 입니다. 아래 주제 중 1개를 선택하여 작성해주세요.
주제 1
6-1 프로토타입의 개념 이해
주제2
6-1 프로토타입의 개념 이해
주제3
6-2 프로토타입 체인
주제4
6-2 프로토타입 체인
주제5
프로토타입 관련 자유 주제
Beta Was this translation helpful? Give feedback.
All reactions