이론/자바 풀스택 국비수업
220512 Javascript 7
달거북씨
2022. 6. 22. 03:16
1. 객체와 변수
1-1. 빈 객체 생성
빈 객체를 만드는 것은 블록괄호{}를 지정하는 것으로 표현
let people = {};
1-2. 변수 추가
객체 안에 추가되어 있는 변수를 멤버변수 혹은 프로퍼티라고 한다.
변수 추가를 위해서는 "객체이름.변수명 = 값;"의 형식을 사용한다.
선언을 위한 별도의 var, let, const 키워드는 사용하지 않는다.
people.name = "hkd";
people.gender = "남자";
[예제 코드]
// 객체생성
let people = {};
// 객체안에 변수 포함
people.name = "hkd";
people.gender = "남자";
// 변수 사용
document.write("<h1>" + people.name + "님은 " + people.gender + " 입니다.</h1>");
▶ hkd님은 남자 입니다. 출력됨
1-3. 객체 생성 및 값 꺼내기
객체는 {key:value}의 모임이다.
[예제 코드]
// 객체 생성 방법 1 - 생성과 동시에 key:value 할당
let grades = {
"abc" : 10, "def" : 6, "ghr" : 8
};
// 객체 값 출력 방법 1 : key값을 지정하면 value값이 출력된다.
document.write("<h1>" + grades.abc + "</h1>");
document.write("<h1>" + grades.def + "</h1>");
document.write("<h1>" + grades.ghr + "</h1>");
document.write("--------------------------");
// 객체 값 출력 방법 2
document.write("<h1>" + grades["abc"] + "</h1>");
document.write("<h1>" + grades["def"] + "</h1>");
document.write("<h1>" + grades["ghr"] + "</h1>");
document.write("--------------------------<br>");
// 객체 생성 방법 2 - new Object()로 생성 후 key:value 할당
let grades2 = new Object();
grades2['abc'] = 10;
grades2['def'] = 6;
grades2['ghr'] = 20;
// 객체 값 출력 방법 3 - key와 value 모두 출력
for( key in grades2 ){ // grades2 객체 안 key 개수 만큼 for문을 돈다.
document.write("key : " + key + ", value : " + grades2[key] + "<br/>")
}
[출력 결과]
1-4. 함수가 선언된 변수
자바스크립트의 변수는 선언 시에 데이터 형이 결정되지 않기 때문에 함수를 대입하는 것도 가능하다.
이렇게 생성된 변수는 함수와 동일한 사용 방법을 갖는다.
[예제 코드]
// 일반적인 함수의 선언
function myFunction(){
document.write("<h1>Hello, javascript</h1>");
}
// javascript는 함수와 변수가 동급
// 따라서 함수의 이름을 변수에 대입할 수 있다.
let value = myFunction;
// 함수가 대입된 변수는 그 자신이 함수처럼 동작한다.
value(); // Hello, javascript
document.write("-------------------------------");
// 함수를 변수에 대입할 수 있기 때문에,
// 처음부터 변수에 함수의 내용을 대입하는 것이 가능하다.
let value2 = function(){
document.write("<h1>Hello~ Javascript!</h1>")
};
value2(); // Hello~ Javascript!
1-5. 객체 안의 객체 / 객체 안의 함수
[예제 코드]
let grades = {
'list' : { 'aaa' : 10 , 'bbb' : 6, 'ccc' : 80 },
'show' : function() {
document.write('Hello World');
}
};
document.write(grades); // [object Object]
document.write(grades['list']); // [object Object]
document.write(grades['list']['aaa']); // 10
document.write(grades.list); // [object Object]
document.write(grades.list.aaa); // 10
document.write(grades['show']); // function() { document.write('Hello World'); }
grades['show'](); // Hello World
grades.show(); // Hello World
▶ 객체 안의 객체의 정확한 key를 지정해주지 않으면 [object Object]로 출력되어 값 확인을 할 수 없다.
▶ 객체 안에 함수가 value로 들어갔을 때, key를 출력시키면 함수 전체 내용이 출력된다.
▶ 함수를 사용하기 위해선 객체[key]();의 형태나 객체.key();의 형태로 사용해야 한다.
1-6. this
객체 안에 포함된 메서드에서 다른 메서드를 호출하거나 변수를 호출할 때 사용
[예제 코드]
let people = {};
people.name = 'hkd';
people.gender = '남자';
// 객체안에 함수 포함시키기
people.sayName = function(){
// 객체 안에 포함된 함수에서, 멤버변수에 접근하기 위해서는
// this라는 예약어를 사용해야 한다
document.write('<h1>' + this.name + '</h1>');
};
peple.sayName(); // hkd
[실습문제 1]
// 1. people객체에 gender가 출력되는 sayGender()함수 생성
people.sayGender = function(){
document.write('<h1>' + this.gender + '</h1>');
};
people.sayGender(); // 남자
document.write('-------------------------------');
// 2. people객체에 saySomething() 함수 생성(param1), document.write로 출력
people.saySomething = function(param1){
document.write('<h1>' + param1 + '</h1>');
};
people.saySomething("hello world"); // hello world
document.write('-------------------------------');
// 3. people객체에 sayInfo() 함수 생성,
// getter를 이용하여 다음과 같이 출력 -> <h1> hkd 님은 남자 입니다. </h1>
people.sayInfo = function(){
document.write('<h1>' + this.getName() + " 님은 " + this.getGender() + ' 입니다.</h1>');
};
people.getName = function(){
return this.name;
};
people.getGender = function(){
return this.gender;
};
people.sayInfo(); // hkd 님은 남자 입니다.
[실습문제 2]
/*
this키워드를 사용해서 for문 사용해서, grades.show() 호출시
a:10
b:20
c:30
을 출력하도록 하라
*/
let grades = {
'list' : {'a':10, 'b':20, 'c':30},
'show' : function(){
for( let key in this.list ){
document.write(key + " : "
+ this.list[key] + "<br>");
}
}
};
grades.show(); // a : 10 <br> b : 20 <br> c : 30
1-7. 생성자
함수에 new 키워드를 붙여 실행한다.
함수 이름의 첫 글자는 대문자로 시작한다.
// 일반적인 함수 생성
let person = {};
person.name = 'hkd';
person.introduce = function(){
return 'My name is ' + this.name;
};
document.write( person.introduce() ); // My name is hkd
document.write('------------------');
// 생성자 이용
function Person2(){};
let p = new Person2();
p.name = 'hkd';
p.introduce = function(){
return 'My name is ' + this.name;
};
document.write(p.introduce()); // My name is hkd
document.write('------------------');
// 생성자를 통한 객체의 초기화
function Person(name){
this.name = name;
this.introduce = function(){
return 'My name is ' + this.name;
};
}
let p1 = new Person('abc');
document.write(p1.introduce() + "<br>"); // My name is abc
let p2 = new Person('def');
document.write(p2.introduce() + "<br>"); // My name is def
728x90