#React탐라 헤르미온느 2일차 #객체

최민재·2023년 4월 5일
0

React 탐라 스터디

목록 보기
2/10

객체

객체는 2가지 방법으로 만든다.

  1. lel person = new Object( ) // 객체 생성자 방식

  2. let person = { }; // 객체 리터럴 ( 중괄호 이용해서 만드는 것)

객체 리터럴 방식

let person = {
   key: "Value",  // property 
   key1: "Value2"
   }; 
   
console.log(person)
let person = {
	key: "Value",
    name: "최민재",
    age: 32
    key3: true,
    key4: [1,2,3],
    key5: function ( ) { }
};

.

  • 점 표기법 : property에 접근하는데 점을 이용해서 접근
    console.log(person.key1); //최민재
    console.log(person.key2); //123

  • 괄호 표기법 ( 주의 괄호 안에 무조건 큰따옴표 써줘야 한다. )
    console.log(person["name"];
    console.log(person["age"];
    console.log(person["key"];
    .

  • 괄호 표기법 쓰기 좋은 경우 - 함수로 이 객체에 이 property에 key를 통해서 value를 받아오는 그런 함수가 필요하다고 할때 .

let person = {
	name: "최민재",
    age: 32
};  //객체 리터럴 방식

// 호이스팅
console.log(getPropertyValue("name"));

function getPropertyValue (key) {
	return person[key];
}

,

객체 생성 이후 property 추가, 수정, 삭제

1. property 추가 ( 점 , 괄호 표기법 )

let person = {
	name: "최민재",
    age: 32
};  //객체 리터럴 방식

person.location = "한국"; // 점 표기법으로 추가할 수 있다. 
person["gender"]="남성"; // 괄호 표기법도 가능.
console.log(person); // 하면 객체 property에 추가 된다.

< name: "최민재"
  age: 32
  location: "한국"

2. property 수정

person.name = "최망고";
person["age"] = 30;

.

여기서 잠깐

let person 에서 let 을 const 로 바꾸면 오류가 날 것 같지만
상수인 person을 바꾸는게 아니라 객체의 property를 속성을 바꾸는 것이기 때문에 오류가 나지 않는다.
.

3. property 삭제 - null

delete person.age;
delete person["name"]

이렇게 삭제하는 방법은 실제로 메모리에서 값이 지워지지 않는다.
그래서 delete 보다는

person.name= null;

이렇게 하면 메모리에서도 삭제된다.

객체 안의 함수

let person = {
	name: "최민재", // 멤버 ( 함수가 아닌 property )
    age: 32, // 멤버
    say: function ( ) {  
      console.log("안녕")
    }  // 메서드 -> 방법 
};  //객체 리터럴 방식

//객체의 함수 호출
person.say( )
person["say"]( )

.

안녕 나는 ${this.name}이야

let person = {
	name: "최민재", 
    age: 32,
    say: function ( ) {  
      console.log(`안녕나는 ${this.name}`);
      //console.log(`안녕나는 ${this.["name"]}`);
    }  // say 라는 메서드 
};  

.

객체에 존재하지 않는 property 에 접근하면? 안 좋다

console.log(person.gender);
undefined 반환.

접근하지 않는 걸 추천한다.

property가 존재하는지 확인하는 방법은? in 연산자

console.log(`name : ${"name" in person}` );
< name : true

console.log(`name : ${"gender" in person}` );
< gender: false
profile
최코딩 블로그

0개의 댓글

관련 채용 정보