김숭늉 마음대로

자바스크립트의 객체 (javascript object), 객체 메서드(object method) 본문

IT/JavaScript

자바스크립트의 객체 (javascript object), 객체 메서드(object method)

김숭늉이 2023. 9. 14. 18:30
728x90

 

 

 

 

 

 

안녕하세요. 오늘도 김숭늉입니다.

이번글에서는 자바스크립트의 객체에 대해 알아보겠습니다. 레쓰고~

 

 

 


자바스크립트의 객체란? (javascript object)

 

키와 밸유로 이루어진 프로퍼티의 정렬되어있지 않은 집합을 말한다.

(프로퍼티 값은 함수로도 올수있고, 이러한 프로퍼티는 메소드라고 함)

 

 

# 배열 (array)와 객체(object)의 차이 ?

배열은 명시하는 데이터 위치로 엑세스하지만 객체에서는 우리가 붙인 이름을 통해 데이터에서 접근 할수 있음,

 


const seungyeon = {
firstName: "seungyeon", // 키 : 밸유 (값)
lastName: "kim",
age: 2037 - 1989,
friends: ["minbi", "mionhyeok"],
};

자바스트립트 객체 (javascript object)

 

⬆️ 콘솔에 객체를 찍어보면 알파벳순으로 정렬이됨 (그래서 객체에서는 배열의 순서가 중요하지 않음!)

 

 


객체의 프로퍼티에 접근하는 방법 

 

 

1) 점표기법 (dot notation) : 개체로 속성을 얻는 방법 첫번째는 .점을 이용

const seungyeon = {
firstName: "seungyeon", // 키 : 밸유 (값)
lastName: "kim",
age: 2037 - 1989,
friends: ["micheal", "minbi", "mionhyeok"],
};
 
console.log(seungyeon.lastName); // 점뒤에 실제 속성이름을 써야함, kim이 출력됨

 

 

2) 괄호표기법(braket notation) : 브라켓( [] )을 이용


console.log(seungyeon["lastName"]); // kim

const nameKey = "Name";

console.log(seungyeon["first" + nameKey]); // seungyeon
console.log(seungyeon["last" + nameKey]); // kim

 


const interestedin = prompt(
"What do you want to know about me? choose between firstName , LastName, age and friends"
);
console.log(seungyeon[interestedin]); // age를 프롬프트 창에 치면 나이가 나옴

if (seungyeon[interestedin]) {
//
console.log(seungyeon[interestedin]);
} else {
console.log("wrong request");  //if else 구문 사용 
}

 

 


객체에 프로퍼티 추가하는 방법

동일하게 점과 브라켓을 이용하여 추가할수 있다.

seungyeon.location = "Seoul";
 
seungyeon["twitter"] = "@asdf";
 
console.log(seungyeon);

 

const seungyeon = {
firstName: "seungyeon", // 키 : 밸유 (값)
lastName: "kim",
age: 2037 - 1989,
friends: ["micheal", "minbi", "mionhyeok"],
};
 
console.log(
`${seungyeon.firstName}, has ${seungyeon.friends.length} friends, his best friend is called ${seungyeon.friends[0]}`
);             
 // seungyeon, has 3 friends, his best friend is called micheal 

 


객체 매서드 (object method)

 

객체의 저장된 밸유값이 함수 일때 객체의 매서드라고 부른다

 
const jonas = {
firstName: "Jonas",
lastName: "Schmedtmann",
age: 2037 - 1991,
job: "teacher",
friends: ["Michael", "Peter", "Steven"],
hasDriversLicence: true,

calcAge: function (birthYear) {.  // 객체의 매서드
return 2037 - birthYear;
},
console.log(jonas.calcAge(1989)); // 48
console.log(jonas["calcAge"](1989)); // 48

 

// this의 사용

const jonas = {
firstName: "Jonas",
lastName: "Schmedtmann",
birthYear: 1989,
age: 2037 - 1991,
job: "teacher",
friends: ["Michael", "Peter", "Steven"],
hasDriversLicence: true,
 
calcAge: function () {
return 2037 - this.birthYear; // manually 객체 이름을 일일이 입력할 필요 없음 
},
};
 
console.log(jonas.calcAge()); // 48
console.log(jonas["calcAge"]()); // 48

 

// 매서드를 통해 프로퍼티 추가 

calcAge: function () {
console.log(this); // jonas라는 객체 전부를 불러옴
this.age = 2037 - this.birthYear;
return this.age; // jonas라는 객체에 추가 !
},

 

// getSummary라는 프로퍼티를 생성하여 콘솔창에 'Jonas is a 39 yesr old. teacher, and he has a driver's license"문구 출력

 
const jonas = {
firstName: "Jonas",
lastName: "Schmedtmann",
birthYear: 1989,
job: "teacher",
friends: ["Michael", "Peter", "Steven"],
hasDriversLicence: true,
 
calcAge: function () {
this.age = 2028 - 1989;
return this.age;
},

getSummary: function () {
return `${this.firstName} is a ${this.calcAge()} yesr old. ${
this.job
}, and he has ${this.hasDriversLicence ? "a" : "no"} driver's license`;
},
};
 
 
//challenge
console.calcAge(); // 호출
console.log(jonas.age); // 39

console.log(jonas.getSummary());  /// Jonas is a 39 yesr old. teacher, and he has a driver's license

 


문제

 

1. 객체를 통해 mark와 john의 풀네임, 몸무게, 키를 작성

2. caclBMI를 통해 몸무게와 키로 BMI를 계산하고 객체 내 프로퍼티로 추가 

3. 콘솔창에 mark와 john의 bmi를 비교하여 문구 노출

    (문구 예시 : Mark Miller's BMI (27.309968138370508) is higher than John Smith's (24.194608809993426)!)


const mark = {
fullName: "Mark Miller",
mass: 78,
height: 1.69,
calcBMI: function () {
this.BMI = this.mass / (this.height * this.height);
return this.BMI;
},
};

const john = {
fullName: "John Smith",
mass: 92,
height: 1.95,
calcBMI: function () {
this.BMI = this.mass / (this.height * this.height);
return this.BMI;
},
};

console.log(mark.BMI); // undefined
mark.calcBMI(); // 호출
john.calcBMI(); // 호출 
console.log(mark.BMI); // 27.309968138370508
console.log(john.BMI); // 24.194608809993426

console.log(
mark.calcBMI() > john.calcBMI()
? `${mark.fullName}'s BMI (${mark.BMI}) is higher than ${john.fullName}'s (${john.BMI})!`
: `${john.fullName}'s BMI (${john.BMI}) is higher than ${mark.fullName}'s (${mark.BMI})!`
);

 

 

그럼 오늘도 좋은하루 보내세요~

 

 

 🤍 이글은 유데미 The Complete JavaScript Course 2023: From Zero to Expert! 습하며 정리하여 공유하는글 입니다.🤍

 

 

 

 

728x90
반응형