JavaScript
Prototype
Jveloper
2019. 5. 7. 08:25
Array.~~~() : 클래스에서만 작동 // Array.prototype.~~~() : 인스턴스에서만 작동
Array.prototype.~~~() : 인스턴스에서만 작동하는거에 대해 알아보자
ex)

그렇다면 인스턴스란 무엇인가?
'new Array(1,2,3)' 또는 'let array = [1,2,3]' 이것들은
Array.prototype( 원본 ) 이 있기때문에
만들어지는 복사본(즉, 인스턴스)이다
ex) prototype이 붕어빵 틀이라면 new Array(1,2,3) , [1,2,3] 이 녀석들이 계속 복사될수 있는 붕어빵이라고 생각하면 편하다
Array.prototype.join.call([1,2,3], '-');
// "1-2-3"
[1,2,3].join('-');
// "1-2-3"
//즉, Array.prototype 은 [1,2,3]
원본에 새로운 메소드를 입힐수 있다
function ProtoExam(name, size){
this.name = name;
this.size = size;
}
ProtoExam.prototype.see = function(){
return `${this.name} is ${this.size}`;
}
let food1 = new ProtoExam('cookie', 'small'); // ProtoExam {name: "cookie", size: "small"}
let food2 = new ProtoExam('pizza', 'big'); // ProtoExam {name: "pizza", size: "big"}
food2.see(); // pizza is big
see라는 메소드를 입힌걸 확인할 수 있다
prototype은 원본이라는것을 잘 기억하자