📌this

함수의 실행 컨텍스트

함수는 전역으로 선언되고 윈도우랑 바인딩된다.
그후 함수를 실행 할 때 함수 내부에서는 또 다른 함수 실행 컨텍스트(환경)가 만들어진다.

📌Object

🏷️표기법

// 점(.) 표기법
// authUser 객체의 프로퍼티에 접근해 Console에 출력해봅니다.
 console.log( authUser.uid );
 console.log( authUser.permission );
 console.log( authUser.email );

// 대괄호([]) 표기법
// 대괄호 표기법을 사용해 접근 Console에 출력해봅니다.
console.log( authUser['uid']);
console.log( authUser['email']);
console.log( authUser['name']);

⚠️ 변하는 키를 받아야 할 땐 점 표기법말고 대괄호를 사용해야 한다.

⚒️클래스 객체 생성하기

class User{
  constructor(name,email){
    this.name = name;
    this.email = email
  }
}

const user3 = new User('동혁')

⚒️함수로 객체 생성하기

/* shorthand property (단축 프로퍼티)  */
function createUser(
  name,
  email,
  computedProp = 'phone',
  number = '010-0000-0000'   
) {
  return {
    name: name,
    email: email,
    [computedProp]: number
  }

}
const user1 = createUser(
  '진승',
  'victory',
  'tel',
  '010-1234-5678'
)

🏷️프로퍼티 나열

// 프로퍼티 나열

// key만 모아놓은 배열
let keyArray = Object.keys(authUser);
let valueArray = Object.values(authUser);

function getProp(object) {
  if(typeof object !== 'object') {
    throw new Error('getProp 함 수의 매개변수는 객체 타입이어야 합니다')
  }
  return Object.keys(object);
}
/* --------- Object.keys를 사용하지 않고 키만 배열로 담아주는 함수 만들기 -------------------- */
function getP(object) {
  let result = [];

  for(let key in object) {
    if(({}).hasOwnProperty.call(object, key)) {
      result.push(key)
    }
  }

  return result;
}

🏷️remove와 delete

removedelete
null(비우기)없앰
authUser.name = nulldelete authUser.uid
function removeProperty(object, key) { 
  if(typeof object !== 'object') {
    throw new Error ('....')
  }

  if(key === 'all') {
    for(let key of Object.keys(object)) {
      object[key] = null;
    }
      return object
    }

    object[key] = null;

    return object;
  }

function deleteProperty(object, key) {

  if(isEmptyObject(object)) {
    return;
  }
  delete object[key];
  return  object;
}
// 객체가 프로퍼티를 포함하는 지 유무를 반환하는 유틸리티 함수 isEmptyObject 작성
function isEmptyObject(object) { // length를 사용하여 비었는지 확인
// 실행 시, object가 비어있다면 true를 반환하고, 그렇지 않으면 false를 반환.
  return !(Object.keys(object).length); // 1
/*--------------------------------------*/
 if(Object.keys(object).length===0) { // 2
  return true;
 }
   return false;
/*----------------------------------------------------*/
  return Object.keys(object).length === 0 ? true: false // 3
}

🏷️구조분해할당

배열의 구조분해할당 : 순서가 정해져 있음, 변수의 이름을 바꿀 수 있다.
객체의 구조분해할당 : 순서가 정해져 있지 않음, 선언은 같은 변수로 지정해야 하고 :을 사용하여 변수를 바꿀 수 있다. 기본값도 할당가능.

배열 구조분해할당

let color = ['#ff0000', '#2b00ff', '#00ff02'];

let [red, blue, green] = color // 순서 중요! let [,,g] = color => green이 담김
                               // let red = color[0];
                               // let blue = color[1];
                               // let green = color[2];

  for(let [key, value] of Object.entries(authUser)) {
     let key = keyValue[0]
     let value = keyValue[1]
     console.log(key)
  }
/*-------------------------------------------------------------------*/
 const [a,b,c,d] = document.querySelectorAll('nav li button')
 a.addEventListener('click', ()=> {})
 b.addEventListener('click', ()=> {})
 c.addEventListener('click', ()=> {})
 d.addEventListener('click', ()=> {})

객체 구조분해할당

const salaries = {
  권헤미: 50,
  이수연: 3000,
  강예나: 500,
  김태일: 700
}
const { 권혜미, 이수연, 강예나, 김태일} = salaries // const 권혜미 = salaries.권헤미
console.log(권혜미)

function setElementCss(options) {
  const {width:w, height:h = 10, overflow, color} = options;
  console.log(w, color);
}
/*--------------------------------------------------------------*/
  function setElementCss(options) { //객체를 던지면
    console.log(options.width, options.color) // 순서에 상관없이 사용가능
  }

setElementCss({
  width: 100,
  height: 200,
  overflow: false,
  color: 'orange'
})

🏷️복사(copy) vs. 참조(reference)

원시값은 복사 객체는 참조

객체 복사

// 객체 복사
// 1. for ~ in 문을 사용한 복사

// 얕은 복사
const cloneObject = {};

for (const key in messenger) {
  cloneObject[key] = messenger[key];
}

// 2. Object.assign()을 사용한 복사
const copyObject = Object.assign({}, messenger);

// 3. 전개 연산자(...)를 사용한 복사
const spreadObject = { ...messenger };

// 4. 객체를 복사해주는 유틸 함수
 function copyedObject(object) {
   return {...object} // or Object.assign({}, object)
 } //아래는 화살표 함수로 바꾼 것 

// copyedObject라는 함수는 object를 매개변수로 받고 Object.assign()을 통해서 전달받은 object를 복사해서 값을 반환하는 함수다.
const copyedObject = object => Object.assign({}, object); 

const newObject = copyedObject(messenger);
console.log(newObject)

// 객체 병합(합성)
const cssMapA = {
  color: '#4b004b',
  margin: '0 auto',
};

const cssMapB = {
  display: 'flex',
  flexFlow: 'column',
  justifyContent: 'center',
  padding: '0.4em 0.62em',
  color: '#3f9e97',
};

let combinedCssMap = {...cssMapA, ...cssMapB}; // 중복된 값이 있으면 뒤에 값으로 덮여 쓰여진다.
// ==  let combinedCssMap = Object.assign({}, cssMapA, cssMapB)

중첩 객체 복사

// 중첩된 프로퍼티에 객체를 포함하는 객체 복사
// 얕은 복사 vs. 깊은 복사
const containerStyles = {
  'min-height': '100vh',
  'max-width': {
    sm: '90%',
    md: 640,
    lg: 960,
    xl: 1120,
    xxl: 1140,
  },
};

// let copyedContainerStyles = {...containerStyles};  얕은 복사
// let copyedContainerStyles = cloneDeep(containerStyles);  깊은 복사

// 1. 깊은 복사 유틸리티 함수 (재귀함수)
function cloneDeep(object) {
  return Object.fromEntries(
    Object.entries(object).map(([key, value]) => {
      let type = typeof value;
      if (value && type === 'object') {
        value = cloneDeep(value);
      }
      return [key, value];
    })
  );
}
profile
진주링딩동🎵

0개의 댓글