Notice
Recent Comments
Recent Posts
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Today
Total
관리 메뉴

기록 > 기억

[JavaScript] 객체 생성 방법 (리터럴, 생성자) 본문

IT국비지원

[JavaScript] 객체 생성 방법 (리터럴, 생성자)

BY SON 2021. 10. 4. 18:44

객체 생성 방법

 

리터럴 객체 → 객체 선언과 동시에 값 초기화

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 객체 

 

Comments