오즈코딩스쿨 초격차캠프 백엔드 14일차

Hyemin Kim·2023년 12월 27일
0

✅ 1. DOM구조란

DOM은 Document Object Model(문서 객체 모델)의 약자로, 웹 페이지의 구조를 나타내는 계층적인 트리 구조를 의미합니다. 이 모델은 HTML, XML 문서의 각 요소를 객체로 표현하고, 이들 객체 간의 관계를 정의하여 스크립트 언어들이 문서의 내용, 구조, 스타일 등을 동적으로 조작할 수 있게 해줍니다.

기본적으로 DOM은 세 가지 주요 요소로 구성됩니다.

  1. 문서 노드(Document Node): 문서 전체를 나타내며, 주로 <html> 요소입니다.
  2. 요소 노드(Element Node): HTML 요소를 나타내며, 문서 내의 모든 HTML 요소가 이에 해당합니다.
  3. 텍스트 노드(Text Node): HTML 요소의 텍스트를 나타냅니다.

DOM은 이러한 노드들을 트리 구조로 구성하여 각 노드에 대한 접근과 조작을 가능하게 합니다. JavaScript와 같은 스크립트 언어를 사용하여 DOM에 접근하고 조작함으로써 동적인 웹 페이지를 만들 수 있습니다.

- What is a DOM structure

The DOM (Document Object Model) structure refers to the hierarchical tree-like representation of a document in web development. It represents the structure of an HTML or XML document, organizing it into a tree of objects that can be manipulated using programming languages like JavaScript. The DOM structure consists of various nodes, each representing an element, attribute, or piece of text in the document.

The key components of the DOM structure include:

  1. Document Node: Represents the entire document.
  2. Element Node: Represents HTML or XML elements, forming the main building blocks of the document.
  3. Attribute Node: Represents attributes of elements.
  4. Text Node: Represents the text content within elements.

The DOM structure allows developers to access, manipulate, and update the content, structure, and style of a web page dynamically. This manipulation is commonly done using scripting languages, particularly JavaScript, to create interactive and dynamic web applications.

✅ 2. 호스트객체와 내장 객체의 차이점

호스트 객체와 내장 객체는 JavaScript 환경에서 다른 역할을 하는 객체들을 나타냅니다.

  1. 호스트 객체 (Host Objects):

    • 호스트 객체는 JavaScript가 실행되는 환경에 따라 제공되는 객체로, 브라우저 환경에서는 window, document, navigator 등이 있습니다.
    • Node.js 환경에서는 파일 시스템을 다루는 fs, 네트워크를 다루는 http 등이 호스트 객체에 해당합니다.
    • 호스트 객체는 해당 환경에서 제공하는 API를 통해 사용할 수 있습니다.
    • 예시: 브라우저에서 제공하는 window 객체는 호스트 객체의 일종입니다.
  2. 내장 객체 (Built-in Objects):

    • 내장 객체는 JavaScript 언어 자체에서 기본적으로 제공하는 객체들로, 모든 JavaScript 환경에서 사용 가능합니다.
    • 대표적인 내장 객체에는 Object, Array, String, Number, Math 등이 있습니다.
    • 이러한 객체들은 JavaScript 엔진에 의해 미리 정의되어 있어서 별도의 선언 없이 사용할 수 있습니다.
    • 예시: 배열을 다루기 위해 사용하는 Array 객체는 내장 객체의 일종입니다.

차이점:

  • 호스트 객체는 실행 환경에 따라 다르며, 해당 환경에서 제공하는 기능을 사용합니다.
  • 내장 객체는 JavaScript 언어 자체에 내장되어 있어 어떤 환경에서든 동일하게 사용할 수 있습니다.

이 둘은 JavaScript 코드가 실행되는 환경에 따라 달라지는데, 브라우저에서 실행되는 JavaScript 코드와 Node.js에서 실행되는 코드가 호스트 객체 측면에서 차이를 보입니다.

- Differences between host and built-in objects

  1. Host Objects:

    • Definition: Host objects are objects provided by the environment in which JavaScript runs. In a web browser, the host objects include window, document, and others provided by the browser environment. In Node.js, they might include objects related to the file system or network.
    • Example (Browser): window, document, navigator.
    • Example (Node.js): fs (file system), http (HTTP module).
  2. Built-in Objects:

    • Definition: Built-in objects are standard objects that are part of the JavaScript language specification itself. They are available in any JavaScript environment, whether it's a browser or Node.js.
    • Example: Object, Array, String, Number, Math.

Differences:

  • Source: Host objects come from the environment (browser, Node.js), while built-in objects are part of the JavaScript language.
  • Availability: Host objects' availability depends on the environment, whereas built-in objects are universally available in any JavaScript environment.
  • Purpose: Host objects provide functionality specific to the environment, while built-in objects offer fundamental features for working with data and logic in JavaScript.

✅ 3. attribute와 property 차이점

  1. 속성(Attribute):

    • 정의: 속성은 HTML 마크업의 일부로, HTML 요소에 대한 추가 정보를 제공합니다. 속성은 항상 HTML 요소의 시작 태그 안에 포함되며 JavaScript와 관련이 없는 HTML의 일부입니다.
    • 예제(HTML): <img src="image.jpg" alt="설명">.
    • 접근(JavaScript): JavaScript에서는 getAttribute 메서드를 사용하여 속성에 접근할 수 있습니다.
  2. 프로퍼티(Property):

    • 정의: 프로퍼티는 JavaScript 객체와 연결된 값으로, HTML 요소를 나타내는 JavaScript 객체의 현재 상태를 나타냅니다. 프로퍼티는 JavaScript를 통해 접근 또는 수정할 수 있습니다.
    • 예제(JavaScript): element.src, element.alt (HTML img 요소의 프로퍼티를 나타냄).
    • 접근(JavaScript): JavaScript의 객체 표기법을 사용하여 직접 프로퍼티에 접근할 수 있습니다 (element.property).

차이점:

  • 위치: 속성은 HTML 마크업의 일부이며 프로퍼티는 JavaScript 객체의 일부입니다.
  • 접근: JavaScript에서는 getAttribute와 같은 메서드를 사용하여 속성에 접근하고, 프로퍼티는 JavaScript 객체 표기법을 사용하여 직접 접근할 수 있습니다.
  • 동적 vs. 정적: 속성은 정적이며 HTML에서 설정되며, 프로퍼티는 동적이며 실행 중에 변경될 수 있습니다.

예시:
다음은 HTML 요소를 고려해봅시다:

<img id="myImage" src="image.jpg" alt="설명">

JavaScript에서:

// 속성에 접근
const srcAttribute = document.getElementById('myImage').getAttribute('src');

// 프로퍼티에 접근
const srcProperty = document.getElementById('myImage').src;

// 프로퍼티 수정
document.getElementById('myImage').alt = '새로운 설명';

요약하면, 속성은 HTML의 일부이며, 프로퍼티는 JavaScript 객체를 통해 HTML 요소와 상호 작용하고 조작하는 데 사용됩니다.

- Differences between attributes and attributes

In the context of HTML and JavaScript, "attribute" and "property" refer to different aspects of working with elements. Let's clarify the differences between them:

  1. Attribute:

    • Definition: An attribute is a part of the HTML markup and provides additional information about an HTML element. Attributes are always included in the opening tag of an HTML element and are not JavaScript-specific.
    • Example (HTML): <img src="image.jpg" alt="Description">.
    • Access (JavaScript): You can access attributes through the getAttribute method in JavaScript.
  2. Property:

    • Definition: A property is a value associated with a JavaScript object, including HTML elements. Properties represent the current state of the object and can be accessed or modified using JavaScript.
    • Example (JavaScript): element.src, element.alt (referring to the properties of an HTML img element).
    • Access (JavaScript): You can directly access properties using JavaScript syntax (element.property).

Differences:

  • Location: Attributes are part of the HTML markup, while properties are part of the JavaScript object representing the HTML element.
  • Access: Attributes are accessed using methods like getAttribute in JavaScript, while properties are accessed directly using JavaScript object notation.
  • Dynamic vs. Static: Attributes are static and set in the HTML, while properties are dynamic and can change during runtime.

Example:
Consider the following HTML element:

<img id="myImage" src="image.jpg" alt="Description">

In JavaScript:

// Accessing attribute
const srcAttribute = document.getElementById('myImage').getAttribute('src');

// Accessing property
const srcProperty = document.getElementById('myImage').src;

// Modifying property
document.getElementById('myImage').alt = 'New Description';

In summary, attributes are part of the HTML, and properties are part of the JavaScript object representing the HTML element, providing a way to interact with and manipulate the element using JavaScript.

✅ 4. 이벤트 루프란

이벤트 루프(Event Loop):

이벤트 루프는 자바스크립트의 비동기 동작을 조율하고, 콜 스택(Call Stack), 메시지 큐(Message Queue), 백그라운드(Task Queue)를 사용하여 이벤트 핸들러 및 비동기 작업을 관리하는 메커니즘입니다. 이것은 브라우저 환경에서는 웹 API들과 함께 동작하며, Node.js에서는 C++로 작성된 libuv 라이브러리를 사용하여 동작합니다.

동작 과정:
1. 콜 스택 (Call Stack): 자바스크립트는 작업을 순차적으로 실행하는 단일 스레드 언어입니다. 함수 호출은 콜 스택에 쌓이고, 실행이 완료되면 스택에서 팝됩니다.

  1. 웹 API 및 백그라운드(Task Queue): 비동기 작업(예: setTimeout, XMLHttpRequest, 이벤트 핸들러)은 웹 API를 통해 백그라운드에서 실행되고, 해당 작업이 완료되면 메시지 큐에 콜백 함수가 추가됩니다.

  2. 이벤트 루프: 콜 스택이 비어있으면, 메시지 큐에서 콜백 함수를 콜 스택으로 이동시킵니다. 즉, 콜백 함수가 실행됩니다.

  3. 반복: 이러한 과정이 계속 반복되어 비동기 및 이벤트 기반 작업이 조율됩니다.

예시:

console.log('Start');

setTimeout(() => {
  console.log('Timeout callback');
}, 1000);

console.log('End');
  1. 'Start'가 콜 스택에 들어갑니다.
  2. setTimeout은 웹 API를 통해 백그라운드에서 1초 뒤에 콜백 함수를 실행 예약하고, console.log('End')가 콜 스택에 들어갑니다.
  3. 'End'가 실행된 후 콜 스택이 비어있게 되면, 이벤트 루프가 메시지 큐에서 콜백 함수를 가져와서 실행합니다.

결과:

Start
End
Timeout callback

이벤트 루프를 통해 비동기 작업과 동기 작업을 조율하여 실시간 및 사용자 이벤트에 대응하면서도 블로킹 없이 프로그램이 계속 실행될 수 있습니다.

- What is an event loop

Event Loop:

The event loop is a mechanism in JavaScript that manages the execution of asynchronous code. It coordinates the call stack, message queue, and background tasks to handle event handlers and asynchronous operations. In a browser environment, it works in conjunction with web APIs, and in Node.js, it uses the libuv library.

How it works:

  1. Call Stack: JavaScript is a single-threaded language that processes tasks sequentially. Function calls are added to the call stack and removed when execution is complete.

  2. Web APIs and Background (Task Queue): Asynchronous tasks (e.g., setTimeout, XMLHttpRequest, event handlers) are executed in the background via web APIs. Once completed, their callback functions are added to the message queue.

  3. Event Loop: When the call stack is empty, the event loop moves callback functions from the message queue to the call stack for execution.

  4. Repeat: This process continues, allowing the orchestration of asynchronous and event-driven tasks without blocking, providing real-time responsiveness.

Example:

console.log('Start');

setTimeout(() => {
  console.log('Timeout callback');
}, 1000);

console.log('End');
  1. 'Start' enters the call stack.
  2. setTimeout schedules a callback function in the background after 1 second, and 'End' enters the call stack.
  3. Once the call stack is empty, the event loop moves the callback function from the message queue to the call stack.

Result:

Start
End
Timeout callback

The event loop allows the coordination of synchronous and asynchronous tasks, enabling programs to continue execution without blocking, and responding to real-time and user events effectively.

✅ 5. TDZ란

TDZ는 "Temporal Dead Zone"의 약자로, 자바스크립트에서 letconst 선언된 변수가 생성되기 전까지 액세스할 수 없는 영역을 가리킵니다.

letconst 선언은 호이스팅(hoisting)되지만, 초기화는 실제 선언 위치에 따라 실행 컨텍스트에서 차단됩니다. 선언부터 초기화까지의 구간을 TDZ라고 부릅니다.

예를 들어:

console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;

위의 코드에서 console.log(x)에서 x에 접근하려고 하지만, 선언은 이루어졌으나 초기화가 되기 전인 TDZ에 있다고 판단하여 ReferenceError가 발생합니다.

TDZ는 letconst를 사용할 때 주의해야 함을 의미하며, 변수가 선언된 위치에서부터 초기화되기 전까지 해당 변수를 사용하려고 할 때 에러가 발생할 수 있음을 나타냅니다.

- What is TDZ

TDZ stands for "Temporal Dead Zone" in JavaScript. It refers to the period between entering scope and the actual variable declaration. During this time, if you try to access a variable declared with let or const, you will get a ReferenceError.

Here's an example:

console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;

In this code, the console.log(x) statement tries to access x before it has been initialized. The variable x is in the temporal dead zone until the declaration let x = 5; is encountered, and any attempt to access it before that point results in an error.

The TDZ is a concept that highlights the restriction on accessing variables declared with let and const before they are initialized in the code.

profile
Full Stack Web Developer

0개의 댓글