프론트엔드 개발/Javascript

자바스크립트 - 객체

snowman95 2021. 8. 18. 22:39
728x90
반응형

객체 (Object)


const student={
  name='bob',
  age=10,
}

# 접근 방법
student.name
student['age']
student['hobby']   # undefined 반환

# 존재 확인 방법
'hobby' in student # boolean(true/false) 반환

# 추가 방법
student.name = 'sam'
student['age'] = 15

# 삭제 방법
delete student.age
delete student['age']

 

반복

const student={
  name='bob',
  age=10,
}

# for in 문 : 객체의 key값을 차례로 반환
for(key in studnet){
  console.log(studnet[key])
}
'bob'
10

 

함수 메소드

# Method
const student={
  name='bob',
  age=10,
  sayHello:function(){
    console.log('hi')
  }
  sayGoodbye(){          # function 키워드 생략 가능
    console.log('hi')
  }
  sayByebye:()=>{        # 화살표 함수로 사용 가능 (가급적 사용하지 말도록)
    console.log('hi')
  }
  sayMyName(){           # (주의) Mehod에서 studnet.name 이렇게 하면 안됨
    console.log(`hi, I'm ${this.name}`)
  }
}
bob.sayMyName()  → 무조건 맨앞에 있는 객체가 this로 결정됨 (this = bob객체)
jane.sayMyName() → (this = jane객체)

※ this는 runtime 에 결정된다.
※ 화살표 함수는 자신의 this를 가지지 않으므로 외부의 this를 가져온다.
   - 브라우저 환경의 this = window
   - Node Js  환경의 this = global

 

단축 프로퍼티

const name='bob'
const age='20'
const student={
  name=name,
  age=age,
}
# 똑같은 변수명을 집어넣을 땐 아래와 같이 단축가능.
const student={
  name,
  age,
}


Computed property (계산된 프로퍼티)

let n = "name"
let a = "age"
const user={
  [n] : "bob",
  [a] : 10
  [1+1] : 2,
  ["a"+"b"] : "c"
}

function createUser(key, value){
  return {
    [key] : value 
  }
}


Object 내장 함수

const user={
  name : "bob",
  age : 10
}

const newUser = user; (복제가 아닌 이름만 새로 붙이는 것임. 같은 객체 가리킴)

newUser = Object.assign({}, user);                ({}에 user객체 합쳐서 새 객체 반환)
newUser = Object.assign({gender : "male"}, user); (gender만 있는 객체에 user객체 합쳐서 새 객체 반환)
newUser = Object.assign(user1, user2, user3);     (user2,3을 합쳐서 user1에 합쳐서 새 객체 반환)

Object.keys(user); 키 배열 반환 ['name', 'age']
Object.values(user); 값 배열 반환 ['bob', 10]
Object.entries(user); 키/값 배열 반환 [ ['name','bob'], ['age',10] ]
Object.fromEntries([ ['name','bob'], ['age',10] ]); 객체로 반환

 

상속

객체.__proto__ = 부모객체

const player={
  hp : 100,
  power : 100,
  attack(){
    console.log('공격');
  },
}
const player1= {
  name : "sponge"
}
player1.__proto__ = player;

Object.keys(player1); 상속된 프로퍼티는 안나온다.
player1.hasOwnProperty(키값); 를 통해 상속된 프로퍼티까지 존재 확인 가능

 

생성자 함수

const newPlayer = function(name){
  this.name = name;
};

player.prototype.hp = 100;
player.prototype.power = 100;
player.prototype.attack = function() {
  console.log('공격');
};

const player1 = new newPlayer('bob');

혹은 아래와 같이 써도 동일하다.

const newPlayer = function(name){
  this.name = name;
};

newPlayer.prototype = {
  constructor: newPlayer,  이 부분을 반드시 써줘야 함.
  hp:100,
  power:100,
  attack() {
  console.log('공격');
  },
};

const player1 = new newPlayer('bob');

특정 프로퍼티를 변경하지 못하도록 해야한다면? (클로저 이용)

const newPlayer = function(newName){
  const name = newName;
  this.getName = function(){
    return name;
  };
};

const player1 = new newPlayer('bob');

 

반응형