티스토리 뷰

front-end/JavaScript

JavaScript 객체

이안_ian 2018. 12. 10. 23:08




반응형

객체 선언 / 호출

객체는 키값을 사용하여 속성(멤버변수) 식별

중괄호를 사용하여 객체생성

[ ](대괄호) 또는 .(점)으로 요소의 값에 접근

속성에 모든 자료형이 올 수 있음, 그 중 함수 자료형인 요소: 메소드

객체 내에서 자신의 속성을 호출할때 반드시 this키워드를 사용

객체의 모든 속성을 출력하려면 for in문을 사용해야함. 

->단순 for문이나 while문으로 출력불가

식별자로 사용할 수 없는 문자(띄어쓰기, 특수문자)를 속성으로 사용할 경우 ' '로 묶어서 선언하고

접근시에는 [ ]만 가능


<div id="obj"></div>
<button onclick="printObj();">실행</button>
<script>
//객체 선언
var Person = {
name: '유병승',
age: 19,
address: "경기도 시흥시",
toString: function () {
return this.name + this.age + this.address;
},
'nick name': '유뱅',
'*^.~*': '윙크',
hobby: ['술래잡기', '고무줄', '말뚝박기', '말타기']
};
console.log(Person.name);
console.log(Person.age);
console.log(Person['address']);
console.log(Person['toString']());
console.log(Person.toString());
console.log(Person['nick name']);
function printObj() {
var area = document.getElementById('obj');
area.innerHTML += Person.toString();
for (var p in Person) {
if (typeof Person[p] != 'function')
area.innerHTML += Person[p] + "<br>";
}
}

</script>


in / with 키워드

in : 객체 내부에 해당 속성이 있는지 확인하는 키워드

with : 코드를 줄여주는 키워드, 호출시 객체명 생략 가능


<div id="print"></div>
<script>
console.log('height' in Person);
if('hobby' in Person)
{
var temp = Person['hobby'].join('->');
document.getElementById('print').innerHTML +=temp;
}
with(Person){
document.getElementById('print').innerHTML +=hobby;
document.getElementById('print').innerHTML +=name;
document.getElementById('print').innerHTML +=age;
}


객체 속성의 추가와 삭제

추가

객체명.속성명 = 값;

객체명['속성명'] = 값;

객체명['속성명'] = function(){

메소드 로직;

[return 값;]

};

삭제

delete(객체명.속성명);

delete(객체명['속성명']);


//Person객체 키, 몸무게 추가하기
Person.score = 190;
Person['height']=186.5;
Person['weight']=60.5;
Person['date']=function(){
console.log(new Date().toLocaleTimeString());
}
for(var p in Person){
console.log("추가 후 : "+Person[p]);
}
Person['date']();
//속성을 삭제
delete(Person['date']);
//Person['date']();


객체배열 활용

생성된 객체를 배열에 넣어 활용

var 변수명 = [ ];  ->배열 생성


데이터 대입

변수명.push( {속성명:'값', 속성명:'값'} );


//객체배열의 활용
var objArr=[];
objArr.push({empName:'조보아',age:24});
objArr.push({pno:10, pname:'갤럭시노트'});
console.log(objArr);
console.log(objArr[0]['empName']);

for(var i=0;i<objArr.length;i++){
for(var t in objArr[i]){
console.log(objArr[i][t]);
}
}


함수활용 객체 생성

함수의 매개변수에 필요한 속성값을 다 받아서 객체를 생성 후 리턴

function 함수명(value1, value2, ...){

var 변수명(객체명) = {

속성명 : 'value1',

속성명 : 'value2'

...

}

return 변수명(객체명);

}


//함수를 이용한 객체 생성
function Product(pname,price,cnt){
var P={
pname:pname,
price:price,
cnt:cnt
}
return P;
}
objArr.push(Product('박보검',10,5));
for(var r in objArr[2]){
console.log(objArr[2][r]);
}


생성자 함수

this 키워드를 사용하여 속성을 생성하는 함수

new라는 키워드를 사용하여 객체 생성

생성자명의 첫 글자는 대문자로 시작

instanceof로 어떤 생성자로 생성되었는지 확인 가능

function 생성자명(value1, value2, ...){

this.속성명 = 'value1',

this.속성명 = 'value2'

...

}

}

//생성자 함수를 통해 객체 생성하기!
function Board(title, comment, date){
this.title = title;
this.comment = comment;
this.date = date;
this.toString = function(){
return this.title+this.comment+this.date.toLocaleTimeString;
}
}
var b1 = new Board('test','test내용',new Date());
console.log(b1.toString());
console.log(b1 instanceof Board);
//생성자는 배열을 넣는다고 instanceof에 나오는게 아니라 아래와 같이 생성자로 생성해줘야 instanceof에 나옴.
b1 = new String();
console.log(b1 instanceof String);
console.log(b1 instanceof Array);


반응형

'front-end > JavaScript' 카테고리의 다른 글

JavaScript 이벤트, 간소한 ajax처리  (0) 2018.12.12
JavaScript BOM와 DOM  (0) 2018.12.12
JavaScript 함수  (0) 2018.12.10
JavaScript 배열의 문법  (0) 2018.12.06
JavaScript 기본문법  (0) 2018.12.06
댓글
반응형
최근에 달린 댓글
글 보관함
Total
Today
Yesterday
최근에 올라온 글
«   2024/05   »
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 29 30 31