Language/Javascript

[자바스크립트 기초 강좌: 100분 완성] 객체

Jonnie 2021. 7. 31. 04:24

객체

{ } 내부에 키(key)와 값(value)로 고정된 속성이 사용됨

const superman = {
	name : 'clark',
	age : 33,
}

각 property는 쉼표로 구분

마지막 쉼표는 생략 가능(하지만 작성 추천)

접근

superman.name

superman['age']

추가

superman.gender = 'male';

superman['hairColor'] = 'black';

삭제 (delete 키워드 사용)

delete superman.hairColor;

단축 프로퍼티

const name = 'clark';
const age = 33;

const superman = {
	name, //name:name
	age, //age:age
	gender:'male',
}

없는 property를 입력할 경우

superman.birthDay;
//undefined

'birthDay' in superman;
//false (in 연산자: property가 있는지 확인 가능)

'age' in superman:
//true

in 연산자: property 존재 유무 확인 가능

for ...in 반복문

for (let key in superman){
	console.log(key)      //superman의 key값들 반환
	console.log(superman[key])
}
const Mike = {
	name: 'Mike',
	age: 30,
};

for (x in Mike){
	console.log(Mike[x])   //Mike['age']
}

=> 'Mike'
    30

이름과 나이를 받아서 객체를 반환하는 함수 만들기

function makeObject(name, age){
	return {
		name : name,
		age : age,
		hobby : 'football'.
	}
}

const Mike = makeObject("Mike", 30);
console.log(Mike);

console.log('age' in Mike)      //true
console.log('birthday' in Mike) //false

method

method: 객체 프로퍼티로 할당된 함수

const superman = {
	name:'clark',
	age:33,
	fly: function(){
		console.log('날아갑니다')
	}
}

superman.fly()
const superman = {
	name:'clark',
	age:33,
	fly(){
		console.log('날아갑니다')
	}
}

superman.fly()

this

const user = {
	name:'Mike',
	sayHello:function(){
		console.log(`Hello, I'm ${this.name}`);   //this==user
	}
}

user.sayHello();   //sayHello()를 호출하면 점 앞의 user가 this가 됨

예시

let boy = {
	name: 'Mike',
}

let girl = {
	name: 'Jane',
}

sayHello:function(){
	console.log(`Hello, I'm ${this.name}`);
}

boy.sayHello();    //I'm Mike
girl.sayHello();   //I'm Jane

화살표 함수를 사용할 경우 this의 의미가 달라지게 됨

화살표 함수는 일반 함수와는 달리 자신만의 this를 가지지 않음

화살표 함수 내부에서 this를 사용하면, 그 this는 외부에서 값을 가져옴

let boy = {
	name: 'Mike',
	sayHello:()=>{
		console.log(this);  //여기서 this는 전역객체가 됨(브라우저 환경: window, node.js: global)
	}
}

boy.sayHello();   //this != boy

 

 

 

강의 출처. 코딩앙마(Youtube)

https://www.youtube.com/watch?v=KF6t61yuPCY&t=229s