Section 6. 객체 다루기

Yejung·2022년 10월 28일
0
post-thumbnail

Shorthand Properties

CSS

background-color: #000;
background-image: url(images/bj.gif);
background-repeat: no-repeat;

margin-top : 10px;
margin-right : 5px;
margin-bottom : 15px;
margin-left : 20px;

// css shorthand properties
background : #000 url(images/bg.gif) no-repeat;

margin: 10px 5px 15px 20px;
const firstName = "javascript";
const lastName = "modern";

const person = {
  firstName: "javascript",
  lastName: "modern",
  getFullName: function(){
  	return this.firstName + ' ' + this.lastName;
  }
}

// js shorthand property
// Concise Method

const person = {
  firstName,
  lastName,
  getFullName() {
  	return this.firstName + ' ' + this.lastName;
  }
} 


Computed Property Name

동적으로 할당되는 객체 프로퍼티

const handleChange = (e) => {
	setState({
      [e.target.name]: e.target.value,
    })
}


Lookup Table

key와 value 형태로 나열된 테이블

if가 너무 길어질 경우
➡ switch case문을 작성하자

// if-else 문
function getUserType(type) {
	if (type === "ADMIN") {
		return "관리자";
	} else if (type === "INSTRUCTOR") {
		return "강사";
	} else if (type === "STUDENT") {
		return "수강생";
	} else {
		return "해당 없음";
	}
}

// switch 문
function getUserType(type) {
	switch (key) {
		case "ADMIN":
			return "관리자";
		case "INSTRUCTOR":
			return "강사";
		case "STUDENT":
			return "수강생";
		default:
			return "해당 없음";
	}
}

// Lookup Table => 강사님이 생각하는 가장 바람직한 케이스
function getUserType(type) {
  const USER_TYPE = {
    ADMIN: "관리자",
    INSTRUCTOR: "강사",
    STUDENT: "수강생",
    UNDEFINED: "해당 없음",
  };

  return USER_TYPE[type] ?? USER_TYPE.UNDEFINED;
}

// 변수 없이 바로 return
function getUserType(type) {
  return {
    ADMIN: "관리자",
    INSTRUCTOR: "강사",
    STUDENT: "수강생",
  }[type] ?? "해당 없음";
}
  
// USER_TYPE을 import 한다면
import USER_TYPE from "./constants/userType.js"
  
function getUserType(type) {
  return USER_TYPE[type] ?? USER_TYPE.UNDEFINED;
}


Object Destructuring

// argument를 순서대로 전달해줘야한다

function Person(name, age, location) {
	this.name = name;
	this.age = age ?? 0;
	this.location = location ?? "korea";
}

const pizza = new Person("pizza", 12, "italy");

// object destructuring  

function Person({ name, age, location }) {
	this.name = name;
	this.age = age;
	this.location = location;
}

// 순서 상관 X
const pizza = new Person({
	location: "italy",
	age: 12,
	name: "pizza",
});

// 필요한 것만 전달해도 ok
const pizza = new Person({
	name: "pizza",
});
  
// name: 필수 parameter, age & location : option
function Person(name, { age, location }) {
	this.name = name;
	this.age = age ?? 0;
	this.location = location ?? "korea";
}

const options = {
	age: 12,
	location: "italy",
};

const pizza = new Person("pizza", options);
const orders = ["first", "second", "third"];

const st1 = orders[0];
const rd1 = orders[2];

const [st2, , rd2] = orders;

const { 0: st3, 2: rd3 } = orders;

+) react props 객체 구조 분해 할당


Object.freeze


Prototype 조작 지양하기


hasOwnProperty


직접 접근 지양하기

profile
이것저것... 차곡차곡...

0개의 댓글