DOM은 Document Object Model(문서 객체 모델)의 약자로, 웹 페이지의 구조를 나타내는 계층적인 트리 구조를 의미합니다. 이 모델은 HTML, XML 문서의 각 요소를 객체로 표현하고, 이들 객체 간의 관계를 정의하여 스크립트 언어들이 문서의 내용, 구조, 스타일 등을 동적으로 조작할 수 있게 해줍니다.
기본적으로 DOM은 세 가지 주요 요소로 구성됩니다.
<html>
요소입니다.DOM은 이러한 노드들을 트리 구조로 구성하여 각 노드에 대한 접근과 조작을 가능하게 합니다. JavaScript와 같은 스크립트 언어를 사용하여 DOM에 접근하고 조작함으로써 동적인 웹 페이지를 만들 수 있습니다.
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:
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.
호스트 객체와 내장 객체는 JavaScript 환경에서 다른 역할을 하는 객체들을 나타냅니다.
호스트 객체 (Host Objects):
window
, document
, navigator
등이 있습니다.fs
, 네트워크를 다루는 http
등이 호스트 객체에 해당합니다.window
객체는 호스트 객체의 일종입니다.내장 객체 (Built-in Objects):
Object
, Array
, String
, Number
, Math
등이 있습니다.Array
객체는 내장 객체의 일종입니다.차이점:
이 둘은 JavaScript 코드가 실행되는 환경에 따라 달라지는데, 브라우저에서 실행되는 JavaScript 코드와 Node.js에서 실행되는 코드가 호스트 객체 측면에서 차이를 보입니다.
Host Objects:
window
, document
, and others provided by the browser environment. In Node.js, they might include objects related to the file system or network.window
, document
, navigator
.fs
(file system), http
(HTTP module).Built-in Objects:
Object
, Array
, String
, Number
, Math
.Differences:
속성(Attribute):
<img src="image.jpg" alt="설명">
.getAttribute
메서드를 사용하여 속성에 접근할 수 있습니다.프로퍼티(Property):
element.src
, element.alt
(HTML img
요소의 프로퍼티를 나타냄).element.property
).차이점:
getAttribute
와 같은 메서드를 사용하여 속성에 접근하고, 프로퍼티는 JavaScript 객체 표기법을 사용하여 직접 접근할 수 있습니다.예시:
다음은 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 요소와 상호 작용하고 조작하는 데 사용됩니다.
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:
Attribute:
<img src="image.jpg" alt="Description">
.getAttribute
method in JavaScript.Property:
element.src
, element.alt
(referring to the properties of an HTML img
element).element.property
).Differences:
getAttribute
in JavaScript, while properties are accessed directly using JavaScript object notation.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.
이벤트 루프(Event Loop):
이벤트 루프는 자바스크립트의 비동기 동작을 조율하고, 콜 스택(Call Stack), 메시지 큐(Message Queue), 백그라운드(Task Queue)를 사용하여 이벤트 핸들러 및 비동기 작업을 관리하는 메커니즘입니다. 이것은 브라우저 환경에서는 웹 API들과 함께 동작하며, Node.js에서는 C++로 작성된 libuv 라이브러리를 사용하여 동작합니다.
동작 과정:
1. 콜 스택 (Call Stack): 자바스크립트는 작업을 순차적으로 실행하는 단일 스레드 언어입니다. 함수 호출은 콜 스택에 쌓이고, 실행이 완료되면 스택에서 팝됩니다.
웹 API 및 백그라운드(Task Queue): 비동기 작업(예: setTimeout, XMLHttpRequest, 이벤트 핸들러)은 웹 API를 통해 백그라운드에서 실행되고, 해당 작업이 완료되면 메시지 큐에 콜백 함수가 추가됩니다.
이벤트 루프: 콜 스택이 비어있으면, 메시지 큐에서 콜백 함수를 콜 스택으로 이동시킵니다. 즉, 콜백 함수가 실행됩니다.
반복: 이러한 과정이 계속 반복되어 비동기 및 이벤트 기반 작업이 조율됩니다.
예시:
console.log('Start');
setTimeout(() => {
console.log('Timeout callback');
}, 1000);
console.log('End');
'Start'
가 콜 스택에 들어갑니다.setTimeout
은 웹 API를 통해 백그라운드에서 1초 뒤에 콜백 함수를 실행 예약하고, console.log('End')
가 콜 스택에 들어갑니다.'End'
가 실행된 후 콜 스택이 비어있게 되면, 이벤트 루프가 메시지 큐에서 콜백 함수를 가져와서 실행합니다.결과:
Start
End
Timeout callback
이벤트 루프를 통해 비동기 작업과 동기 작업을 조율하여 실시간 및 사용자 이벤트에 대응하면서도 블로킹 없이 프로그램이 계속 실행될 수 있습니다.
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:
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.
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.
Event Loop: When the call stack is empty, the event loop moves callback functions from the message queue to the call stack for execution.
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');
'Start'
enters the call stack.setTimeout
schedules a callback function in the background after 1 second, and 'End'
enters 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.
TDZ는 "Temporal Dead Zone"의 약자로, 자바스크립트에서 let
과 const
선언된 변수가 생성되기 전까지 액세스할 수 없는 영역을 가리킵니다.
let
과 const
선언은 호이스팅(hoisting)되지만, 초기화는 실제 선언 위치에 따라 실행 컨텍스트에서 차단됩니다. 선언부터 초기화까지의 구간을 TDZ라고 부릅니다.
예를 들어:
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;
위의 코드에서 console.log(x)
에서 x
에 접근하려고 하지만, 선언은 이루어졌으나 초기화가 되기 전인 TDZ에 있다고 판단하여 ReferenceError가 발생합니다.
TDZ는 let
과 const
를 사용할 때 주의해야 함을 의미하며, 변수가 선언된 위치에서부터 초기화되기 전까지 해당 변수를 사용하려고 할 때 에러가 발생할 수 있음을 나타냅니다.
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.