반응형
컨스트럭터 함수
자바스크립트에서 객체를 생성하는 방법 중 하나.
function SoccerPlayer() {
this.position = "Forward";
}
var VanPersie = new SoccerPlayer();
VanPersie.position; //Forward
이의 장점은 새로운 객체를 만들 때 초깃값을 전달하여 생성할 수 있다.
function SoccerPlayer(name, position) {
this.name = name;
this.position = position;
this.whatIsYourName = function() {
return "My name is " + this.name;
};
this.whatIsYourPosition = function() {
return "My position is " + this.position;
};
}
->name, position 속성을 추가 입력받아 자신의 속성값으로 취하고, 이 둘을 확인할 수 있는 메서드를 추가했다.
//사용법
var player = new SoccerPlayer("Park Ji Sung", "Wing Forward");
player.whatIsYourName(); //"My name is Park Ji Sung"
player.whatIsYourPosition(); //"My position is Wing Forward"
컨스트럭터 속성
새로운 객체를 생성하면 보이지는 않지만 constructor라는 속성이 생긴다. 이는 객체를 만드는데 어떤 객체를 참조했는지에 대한 정보를 가진다.
var player = new player.constructor("Koo Ja Cheol");
player.name; //"Koo Ja Cheol"
instanceof 연산자
특정 객체가 어떤 컨스트럭터를 이용해 만들어졌는지 테스트할 수 있다.
player instanceof SoccerPlayer; //true
player instanceof Object; //true
반응형
'Front-End: Web > JavaScript' 카테고리의 다른 글
클로져(Closure) (0) | 2020.08.31 |
---|---|
내장형 객체 (0) | 2020.08.31 |
객체지향 자바스크립트 (0) | 2020.08.31 |
자바스크립트의 기초 (0) | 2020.08.31 |
JavaScript의 특징 (0) | 2020.08.31 |