자바스크립트에서 함수와 객체는 매우 중요한 개념이다. 두 개념은 자바스크립트 프로그래밍의 핵심으로, 코드의 구조를 명확히 하고, 효율적인 재사용과 관리가 가능하도록 해준다. 각 개념에 대해 자세히 설명할게.
함수는 코드 블록으로, 특정 작업을 수행하도록 정의된 코드 집합이다. 함수는 재사용 가능하며, 특정 동작을 여러 번 호출할 수 있다. 자바스크립트에서 함수는 일급 객체(first-class object)로 취급되므로, 변수에 할당하거나 다른 함수의 인자로 넘길 수 있다.
자바스크립트에서 함수를 정의하는 방법은 크게 3가지가 있다.
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // "Hello, Alice"
함수 표현식은 변수에 함수를 할당하는 방식이다. 함수가 변수에 할당되기 전에 호출할 수 없다는 특징이 있다(호이스팅되지 않음).
const greet = function(name) {
return "Hello, " + name;
};
console.log(greet("Bob")); // "Hello, Bob"
화살표 함수는 ES6에서 도입된 문법으로, 짧고 간결하게 함수를 정의할 수 있다. this 바인딩 방식이 다르므로 주의가 필요하다.
const greet = (name) => {
return "Hello, " + name;
};
console.log(greet("Charlie")); // "Hello, Charlie"
function add(a, b) {
return a + b;
}
let result = add(5, 3); // result는 8이 된다.
console.log(result); // 8
함수는 정의된 후 호출될 때 실행된다. 함수 호출 시 전달되는 값은 인자(argument)라고 부르며, 함수 내의 매개변수와 매칭된다.
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5); // 4와 5가 인자로 전달됨
console.log(result); // 20
자바스크립트에서는 함수 선언이 호이스팅되어, 함수가 선언되기 전에 호출할 수 있다. 하지만 함수 표현식은 호이스팅되지 않는다.
console.log(myFunc()); // 정상적으로 호출됨
function myFunc() {
return "Hello!";
}
객체(Object)는 키(key)와 값(value)의 쌍으로 이루어진 데이터 구조다. 자바스크립트에서 객체는 데이터를 저장하는 데 매우 중요한 역할을 한다. 객체는 속성(프로퍼티)과 메서드(함수)를 가질 수 있다.
객체는 중괄호 {}를 사용해 간단하게 만들 수 있다. 각 항목은 키(key)와 값(value)의 쌍으로 이루어진다.
const person = {
name: "John",
age: 30,
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.name); // "John"
console.log(person.greet()); // "Hello, John"
new Object() 방식객체는 new Object()를 통해서도 만들 수 있지만, 일반적으로 리터럴 방식을 사용하는 것이 더 직관적이고 짧다.
const person = new Object();
person.name = "Jane";
person.age = 25;
person.greet = function() {
return "Hi, " + this.name;
};
console.log(person.name); // "Jane"
console.log(person.greet()); // "Hi, Jane"
객체의 속성에 접근할 때 점(.)을 사용한다.
console.log(person.name); // "Jane"
대괄호 표기법은 속성 이름이 동적으로 결정되거나, 공백을 포함하는 경우에 유용하다.
console.log(person["name"]); // "Jane"
const propName = "age";
console.log(person[propName]); // 25
객체 내의 함수는 메서드라고 불린다. 메서드는 객체의 속성처럼 this를 사용하여 객체의 다른 속성에 접근할 수 있다.
const person = {
name: "Alice",
age: 28,
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.greet()); // "Hello, Alice"
thisthis는 객체 자신을 참조하는 키워드이다. 객체 내에서 메서드가 실행될 때, this는 그 메서드를 호출한 객체를 가리킨다.
const car = {
brand: "Toyota",
model: "Corolla",
displayInfo: function() {
return this.brand + " " + this.model;
}
};
console.log(car.displayInfo()); // "Toyota Corolla"
객체는 런타임 중에도 속성을 동적으로 추가하거나 삭제할 수 있다.
person.country = "USA";
console.log(person.country); // "USA"
delete person.age;
console.log(person.age); // undefined
자바스크립트에서는 객체가 다른 객체의 속성을 상속할 수 있다. 자바스크립트는 프로토타입 기반 상속을 사용한다.
모든 자바스크립트 객체는 내부적으로 프로토타입(prototype)이라는 객체를 참조하고 있다. 객체가 속성이나 메서드를 찾을 때, 해당 객체에서 찾지 못하면 프로토타입에서 찾아본다.
const person = {
name: "Jack"
};
const student = Object.create(person);
student.age = 20;
console.log(student.name); // "Jack" (person 객체에서 상속)
console.log(student.age); // 20
자바스크립트는 생성자 함수(constructor function)를 사용해 객체를 생성할 수 있다. 생성자 함수는 대문자로 시작하는 이름을 가지며, new 키워드를 사용하여 객체를 생성한다.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return "Hi, my name is " + this.name;
};
}
const person1 = new Person("Tom", 30);
console.log(person1.greet()); // "Hi, my name is Tom"