TIL - Javascript Objects, Methods

hayyim0626·2020년 8월 5일
0
post-thumbnail

1. Object

let fasterShip = {
  color: 'silver' ,
  'Fuel Type' : 'Turbo Fuel'
};
console.log(fasterShip);
//Output: { color: 'silver', 'Fuel Type': 'Turbo Fuel' }

2. The ways to acces a key's value

2-1. Accessing Porperties

  • objcetName.keyName를 통해 value를 찾기.
let spaceship = {
  homePlanet: 'Earth',
  color: 'silver',
  'Fuel Type': 'Turbo Fuel',
  numCrew: 5,
  flightPath: ['Venus', 'Mars', 'Saturn']
  };

let crewCount = spaceship.numCrew; //Output:5
let planetArray = spaceship.flightPath; 
//Output: [ 'Venus', 'Mars', 'Saturn' ]

2-2. Bracket Notation

  • objectName[propName];
  • bracket notation[]을 통해 value 찾기.
  • 함수를 이용할 때 용이함.
  • key에 접근하기 위해서는 반드시 괄호를 사용해야 함. 그렇지 않을 경우 error뜬다.
let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  'Active Mission' : true,
  homePlanet : 'Earth', 
  numCrew: 5
 };

let propName =  'Active Mission';

let isActive = spaceship['Active Mission'];

console.log(spaceship[propName]);
//Output: true

3. Property Assignment

  • const로 선언된 object도 새로운 property를 추가하거나 변경할 수 있다.
  • dot operator 또는 bracket notation 사용.
let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
 homePlanet : 'Earth',
  color: 'silver',
  'Secret Mission' : 'Discover life outside of Earth.'
};

//reassign property
spaceship['color'] = 'glorious gold';  //또는
spaceship.color = 'glorious gold';

//add property
spaceship.numEngines = 5;

//delete property
delete spaceship['Secret Mission'];

4. Methods

property: what an object has
method: what an object does

let retreatMessage = 
    'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';

let alienShip = {
  retreat() {
    console.log(retreatMessage)
  },
  
  takeOff() {
    console.log('Spim... Borp... Glix... Blastoff!')
  }
};

alienShip.retreat();

alienShip.takeOff();  //Invoke two methods
/*Output: We no longer wish to conquer your planet. It is full of dogs, which we do not care for.
Spim... Borp... Glix... Blastoff!
*/

5. Nested Objects

  • block안에 여러 Object가 존재하면 ','를 사용한다.
let spaceship = {
  passengers: 
    [{name: 'John'}, 
     {age: 25}, 
     {degree: 'Political Science'}],
  crew: {
    captain: { 
      name: 'Sandra', 
      degree: 'Computer Engineering', 
      encourageTeam() { console.log('We got this!') },
     'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
  },
 }; 
let capFave = spaceship.crew.captain['favorite foods'][0]; // cookies
//array안의 특정 값을 갖는 경우 [index]로 나타낸다.
let firstPassenger = spaceship.passengers[0]; //{name: 'John'}

arry 안에 key:value를 설정하려면 [{key1: value1},{key2: value2},...]로 해야한다.

6. Pass by Reference

  • 특정 object의 property를 변경하는 function은 실제로 object를 영구적으로 변이시킨다.
  • 자바스크립트에서 object와 array는 reference로 전달됨.
  • Pass by Value vs Pass by Reference (밑의 URL 참조)

https://medium.com/@nicegirl/javascript-what-are-a-pass-by-value-and-a-pass-by-reference-2ff627cd401c

let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  homePlanet : 'Earth'
};  //spaceship object에 대한 property

function greenEnergy(obj) {
  obj['Fuel Type'] = 'avocado oil';
};  //greenEnergy function(reference type)

let remotelyDisable = obj => {
  obj.disabled = true;
}; //remotelyDisable function(reference type)

greenEnergy(spaceship); //spaceship object를 greenEnergy function에 참조
remotelyDisable(spaceship); //spaceship object를 remotelyDisable function에 참조

console.log(spaceship);
/*Output:{ 'Fuel Type': 'avocado oil',
  			homePlanet: 'Earth',
  			disabled: true }
*/

7. Looping Through Objects

for...in Method

  • object의 property를 순회하는 데 사용
  • for (let propName in obj(배열인경우 arr)){};
let spaceship = {
    crew: {
    captain: { 
        name: 'Lily', 
        degree: 'Computer Engineering', 
        cheerTeam() { console.log('You got this!') } 
        },
    'chief officer': { 
        name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The tank is full!') } 
        }
    }
}; 

for (let crewMember in spaceship.crew) {
  console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`)
}; 
/*
captain: Lily
chief officer: Dan
medic: Clementine
translator: Shauna
*/

for (let crewMemName in spaceship.crew) {
  console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`)
};
/*
Lily: Computer Engineering
Dan: Aerospace Engineering
Clementine: Physics
Shauna: Conservation Science
*/
//Output: 
//Output: 
profile
내실 있는 프론트엔드 개발자가 되기 위해 오늘도 최선을 다하고 있습니다.

0개의 댓글