기록 > 기억
[JavaScript] 객체 생성 방법 (리터럴, 생성자) 본문
객체 생성 방법
① 리터럴 객체 → 객체 선언과 동시에 값 초기화
let obj1 = {
name : "son",
team : "spurs",
age : 29,
setTeam : function(team) {
this.team = team;
},
getTeam : function() {
return this.team;
}
};
console.log(obj1.getTeam()); //spurs
obj1.setTeam("mancity");
console.log(obj1.getTeam()); //mancity
let obj2 = {}; //let obj2 = new Object();
obj2.name = "hwang";
obj2.team = "wolves";
obj2.age = 26;
obj2.setTeam = function(team) {
this.team = team;
};
obj2.getTeam = function() {
return this.team;
};
console.log(obj2.getTeam()); //hwang
obj2.setTeam("liverpool");
console.log(obj2.getTeam()); //liverpool
② 생성자 객체 → 생성자 함수와 new 연산자 사용
//생성자 함수
function Player(name, team, age) {
//값 초기화
this.name = name;
this.team = team;
this.age = age;
//setter
this.setTeam = function(team) {
this.team = team;
};
//getter
this.getTeam = function() {
return this.team;
}
}
//new 연산자로 인스턴스 생성
let p1 = new Player("son", "spurs", 30);
console.log(p1.name); //son
console.log(p1.team); //spurs
console.log(p1.age); //30
p1.setTeam("mancity");
console.log(p1.getTeam()); //mancity
③ prototype 객체
'IT국비지원' 카테고리의 다른 글
[MySQL] 사용자 등록 / DB 생성 / 권한 부여 (0) | 2021.10.07 |
---|---|
[SQL Client] DBeaver 설치 및 DB 연결 (0) | 2021.10.06 |
[MySQL] MySQL ZIP Archive 설치 (0) | 2021.10.05 |
[JavaScript] 회원가입 유효성 검사 (0) | 2021.10.04 |
[JavaScript] 로또번호 출력하기 (0) | 2021.09.30 |
[JavaScript] 내장 객체 ① Date 객체 (0) | 2021.09.29 |
[JavaScript] 이벤트 (0) | 2021.09.29 |
Comments