21.12.22

binary·2021년 12월 22일
2

일팔공

목록 보기
8/20
post-thumbnail

자바스크립트 객체

자바스크립트는 객체 기반 언어이다. (객체 지향 X)

자바스크립트 객체 구성

  • 프로퍼티: 객체의 고유한 속성 (변수)
  • 메소드(method): 함수
// account 객체
const account = {
  // 프로퍼티
  owner : "pongdang",
  code: "111",
  balance: 35000,
  
  // 메소드, 함수
  deposit: function(){...},
  withdraw: function(){...},
  inquiry: function(){...},
};

자바스크립트 객체 종류

1. 코어 객체

  • 코어 객체 생성은 new 키워드를 이용한다.
let today = new Date(); // 시간 정보를 다루는 Date 타입의 객체 생성
const msg = new String("hello"); // "hello" 문자열을 담은 string 타입의 객체 생성
  • 객체 접근은 점(.) 연산자를 이용한다.
obj.프로퍼티 = 값; // 객체 obj의 프로퍼티 값 변경
변수 = obj.프로퍼티; // 객체 obj의 프로퍼티 값 알아내기
obj.메소드; // 객체 obj의 메소드 호출
  • 자바스크립트 언어가 실행되는 어디서나 사용 가능한 기본 객체이다.
  • Array, Date, String, Math 등

2. HTML DOM 객체

  • HTML 문서에 작성된 각 HTML 태그들을 객체화한 것이다.
  • HTML 문서의 내용과 모양을 제어할 수 있다.
  • w3c의 표준 객체이다.

3. 브라우저 객체

  • window(최상위), location, navigator, history, screen, document
  • BOM(Brower Object Model)에 따르는 객체들이다.
  • 비표준 객체이다.

자바스크립트 배열

여러 개의 원소들을 연속적으로 저장하며 이것을 하나의 단위로 다루는 데이터 구조이다.

배열 생성과 접근

  • []로 배열 만들기
  • Array 객체로 배열 만들기
  • []로 배열을 생성해도 Array 객체로 다루어진다.
// 배열 생성
let cities = ["Seoul", "New York", "Paris"];
let n = [4, 5, 0, -2, 563, 15];

const week = new Array("월", "화", "수", "목", "금", "토", "일");

let fruit = new Array();
fruit[0] = "apple";
fruit[1] = "banana";


// 배열 접근
const name = cities[0]; // name은 "Seoul"
cities[1] = "Japan"; // "New York" 자리에 "Japan" 저장

배열의 원소 개수 구하기

.length 프로퍼티를 이용하여 배열 원소 개수를 구하거나 배열의 길이를 지정할 수 있다.

const num = fruit.length;
console.log(num); // 2

fruit.length = 10;
console.log(fruit.length); // 10

// 여기서 num은 2, fruit.length는 10으로 num은 변하지 않는다. 

Date 객체

  • 시간을 정보는 담는 객체
let now = new Date(); // Wed Dec 22 2021 17:11:28 GMT+0900 (한국 표준시)
let date = now.getDate(); // 22 일
let hour = now.getHours(); // 17 시

let startDay = new Date(2000, 00, 21); // Fri Jan 21 2000 00:00:00 GMT+0900 (한국 표준시)
// 월은 0부터 시작한다. 0은 1월, 1은 2월 ...

String 객체

  • 문자열을 담기 위한 객체이며, 한 번 생성되면 수정이 불가능하다.
  • 문자열 길이는 배열에서 했던 것처럼 .length 프로퍼티를 사용하면 알 수 있다.
  • 문자열을 배열처럼 사용할 수 있다. 접근 방법과 글자의 길이를 구하는 방법도 같다.
// 두 경우 모두 String 객체 생성
const hello1 = new String("Hello"); 
const hello2 = "Hello";

const hello1 = new String("Hello"); 
const helloWorld = hello1.concat("world");
console.log(hello1); // String {'Hello'}
console.log(helloWorld); // 'Helloworld'

console.log(hello1.length); // 5
console.log(hello1[2]); // l

Math 객체

  • 수학 계산을 위한 프로퍼티와 메소드 제공
  • 다른 객체와 달리 new 키워드를 사용하지 않는다.
// 두 경우 모두 String 객체 생성
const sq = Math.sqrt(4); // 4의 제곱근 = 2
const area = Math.PI * 2 * 2; // 반지름이 2인 원의 면적, 12.566370614359172

let m = Math.random() * 100; // m은 0~99.999...보다 작은 실수 리턴
let n = Math.floor(m) // m에서 소수점 이하를 제거한 정수 0~99

사용자 객체 만들기

new Object()로 만들기

  1. new Object()로 빈 객체 생성
  2. 빈 객체에 프로퍼티 추가
    • 프로퍼티 이름과 초기값 지정
  3. 빈 객체에 매소드 추가
    • 메소드로 사용할 함수 미리 작성
    • 새 메소드 추가(메소드 이름에 함수 지정)
const account = new Object();
account.owner = "pongdang";
account.code = "111";
account.balance = 35000;

// 메소드 작성
account.inquiry = inquiry; 
account.deposit = deposit;
account.withdraw = withdraw;

리터럴 표기법으로 만들기

const account = {
  owner = "pongdang";
  code = "111";
  balance = 35000;
  
  // 메소드 작성
  inquiry: function () {
    return this.balance;
  },
  deposit: function (money) {
    return (this.balance += money);
  },
  withdraw: function (money) {
    this.balance -= money;
    return money;
  },

프로토타입

  • 객체의 모양을 가진 틀
  • 붕어빵이 객체라면 프로토타입을 붕어빵을 찍어내는 틀이다.
  • C++, Java에서는 프로토타입을 클래스라고 부른다.
  • Array, Date, String : 자바스크립트에서 제공하는 프로토타입
  • 객체 생성시 'new' 프로토타입 이용

// 프로토타입은 함수로 만든다. 프로토 타입 함수, 생성자 함수라고 불리기도 함
function Account(owner, code, balance) {
  this.owner = owner;
  this.code = code;
  this.balance = balance;

  this.inquiry = function () {
    return this.balance;
  };
  this.deposit = function (money) {
    return (this.balance += money);
  };
  this.withdraw = function (money) {
  this.balance -= money;
    return money;
  };
}


// new 키워드로 객체를 생성한다
const account = new Account("pongdang", "111", 35000);
document.write(`account: ${account.owner},
                         ${account.code}, 
                         ${account.balance} <br>`);

account.deposit(1000);
document.write(`1000원 저금<br>`);
document.write(`account: ${account.owner},
                         ${account.code},
                         ${account.balance} <br>`);

account.withdraw(5000);
document.write(`5000원 출금<br>`);
document.write(`account: ${account.owner},
                         ${account.code}, 
                         ${account.balance} <br>`);

| 실행화면

0개의 댓글