자바스크립트의 객체

June Lee·2021년 3월 10일

JavaScript

목록 보기
3/11

자바에서 클래스는 메서드와 변수로 이루어지는데, 자바스크립트의 객체는 이름과 값으로 구성된 프로퍼티의 집합으로 표현된다. 따라서 함수 역시 프로퍼티(객체 내의 변수)에 할당되는 형식으로 구현된다.

객체 생성 방식


1. Object 객체 사용
객체를 생성하는 첫 번째 방법은 자바스크립트의 내장 객체인 Object를 사용하는 것이다.

new Object()를 하면 빈 객체 {}가 생성되고,

var obj = new Object();

여기에 동적으로 새로운 프로퍼티를 추가하는 방식으로 사용자 정의 객체를 생성할 수 있다.

obj.name = "june";
obj.age = 20;
console.log(obj); // {name: "june", age: 20}

2. 리터럴 형식의 객체

var obj = {
  name: "june",
  age: 20,
  showName: function(){
    console.log(this.name);
  }
}

obj.showName(); // june

3. 함수 === 객체

function add(x, y){
  	return x + y;
}

console.log(add(100, 200)); // 300
add.status = 'ok';
console.log(add.status); // ok

자바스크립트에서는 문자열, 숫자, true/false, null, undefined를 제외한 모든 값이 객체이다. 따라서 함수 형식으로 객체를 생성해줄 수도 있다.

4. 생성자 함수를 이용한 객체 생성
생성자 함수를 이용해 객체를 생성하면, 동일한 객체의 value 값을 바꿔가면 여러 번 생성해야할 때 중복 코드를 줄이고 효율을 높일 수 있다.

function grade(kor, eng, math){
  this.kor = kor;
  this.eng = eng;
  this.math = math;
}

function student(name, grade){
  this.name = name;
  this.grade = grade;
  this.getSum = function(){
    return this.grade.kor + this.grade.eng + this.grade.math;
  }
  this.getAverage = function(){
    return this.getSum() / 3;
  }
  this.toString = function(){
    return this.name + "\t" + this.grade.kor + "\t" + this.grade.eng + "\t" + this.grade.math + "\t" + this.getSum() + "\t" + this.getAverage();
  }
}

var students = [];
students.push(new student("june", new grade(90, 80, 70)));
students.push(new student("spring", new grade(50, 70, 50)));

for(var i in students){
  document.write(students[i].toString()+"<br>");
}

5. class 이용

class Rectangle {
  constructor(w, h){
    this.width = w;
    this.height = h;
  }
  getArea(){
    return this.width * this.height;
  }
}

var rectangle = new Rectangle(5, 7);
console.log(rectangle.getArea()); // 35
console.log(rectangle.width); // 5
profile
📝 dev wiki

0개의 댓글