익명 함수 방식 |
var btn = document.getElementById("aboutW3Btn"); btn.onclick = function(e){ alert("AboutW3에 오신걸 환영합니다."); } |
Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
car.name = Fiat car.model = 500 car.weight = 850kg car.color = white |
car.start() car.drive() car.brake() car.stop() |
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
var car = new Object(); car.name = "Fiat"; car.start = function(){ console.log("Start Car " + car.name); } |
https://www.javatpoint.com/javascript-tutorial
JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a colon).
It is a common practice to declare objects with the const keyword.
Learn more about using const with objects in the chapter: JS Const.
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Object Properties
The name:values pairs in JavaScript objects are called properties:
PropertyProperty Value
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
Accessing Object Properties
You can access object properties in two ways:
or
Example1
Example2
JavaScript objects are containers for named values called properties.
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
PropertyProperty Value
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() {return this.firstName + " " + this.lastName;} |
A method is a function stored as a property.
Example
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this refers to the person object.
I.E. this.firstName means the firstName property of this.
I.E. this.firstName means the firstName property of person.
What is this?
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. |
Alone, this refers to the global object. |
In a function, this refers to the global object. |
In a function, in strict mode, this is undefined. |
In an event, this refers to the element that received the event. |
Methods like call(), apply(), and bind() can refer this to any object. |
The this Keyword
In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
Learn more about this in The JavaScript this Tutorial.
Accessing Object Methods
You access an object method with the following syntax:
Example
If you access a method without the () parentheses, it will return the function definition:
Example
Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword "new", the variable is created as an object:
y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.
You will learn more about objects later in this tutorial.
Document Object Model
문서 객체 모델(DOM)은 HTML과 XML 문서를 위한 프로그래밍 API이다. 문서의 논리적 구조와 문서에 액세스하고 조작하는 방법을 정의합니다.
DOM 규격에서 "문서"라는 용어는 넓은 의미로 사용되는데, XML은 다양한 시스템에 저장될 수 있는 많은 종류의 정보를 표현하는 방법으로 점점 더 많이 사용되고 있으며, 이 중 많은 부분이 전통적으로 문서라기보다는 데이터로 보여질 것이다.
그럼에도 불구하고 XML은 이 데이터를 문서로 나타내며, DOM을 사용하여 이 데이터를 관리할 수 있습니다.
Document Object Model을 사용하여 프로그래머는 문서를 작성 및 작성하고, 문서를 탐색하고, 요소와 내용을 추가, 수정 또는 삭제할 수 있습니다.
HTML이나 XML 문서에서 발견되는 모든 것은 문서 오브젝트 모델을 사용하여 접근, 변경, 삭제 또는 추가할 수 있지만, 특히 내부 서브셋과 외부 서브셋에 대한 DOM 인터페이스는 아직 지정되지 않았다.
W3C 사양으로서, 문서 객체 모델의 한 가지 중요한 목표는 다양한 환경과 응용 프로그램에서 사용할 수 있는 표준 프로그래밍 인터페이스를 제공하는 것이다. Document Object Model은 모든 프로그래밍 언어와 함께 사용할 수 있습니다.
Document Object Model 인터페이스의 정확하고 언어 독립적인 규격을 제공하기 위해 CORBA 2.2 규격에 정의된 대로 OMG IDL로 규격을 정의하기로 결정했다. OMG IDL 규격 외에도 Java 및 ECMAscript(JScript 및 JScript에 기반한 업계 표준 스크립팅 언어)에 대한 언어 바인딩을 제공한다.
참고: OMG IDL은 인터페이스를 지정하는 언어 독립적이고 구현 중립적인 방법으로만 사용됩니다. OMG IDL을 사용한다고 해서 특정 객체 바인딩 런타임을 사용해야 하는 것은 아니다.
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
- An HTML web page has finished loading
- An HTML input field was changed
- An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:
With double quotes:
In the following example, an onclick attribute (with code), is added to a <button> element:
Example
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of its own element (using this.innerHTML):
Example
JavaScript code is often several lines long. It is more common to see event attributes calling functions:
Example
Common HTML Events
Event | Description |
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The browser has finished loading the page |
HTML DOM Events
이벤트 | 설명 | 구분 |
abort | The event occurs when the loading of a media is aborted | UiEvent, Event |
afterprint | The event occurs when a page has started printing, or if the print dialogue box has been closed | Event |
animationend | The event occurs when a CSS animation has completed | AnimationEvent |
animationiteration | The event occurs when a CSS animation is repeated | AnimationEvent |
animationstart | The event occurs when a CSS animation has started | AnimationEvent |
beforeprint | The event occurs when a page is about to be printed | Event |
beforeunload | The event occurs before the document is about to be unloaded | UiEvent, Event |
blur | The event occurs when an element loses focus | FocusEvent |
canplay | The event occurs when the browser can start playing the media (when it has buffered enough to begin) | Event |
canplaythrough | The event occurs when the browser can play through the media without stopping for buffering | Event |
change | The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>) | Event |
click | The event occurs when the user clicks on an element | MouseEvent |
contextmenu | The event occurs when the user right-clicks on an element to open a context menu | MouseEvent |
copy | The event occurs when the user copies the content of an element | ClipboardEvent |
cut | The event occurs when the user cuts the content of an element | ClipboardEvent |
dblclick | The event occurs when the user double-clicks on an element | MouseEvent |
drag | The event occurs when an element is being dragged | DragEvent |
dragend | The event occurs when the user has finished dragging an element | DragEvent |
dragenter | The event occurs when the dragged element enters the drop target | DragEvent |
dragleave | The event occurs when the dragged element leaves the drop target | DragEvent |
dragover | The event occurs when the dragged element is over the drop target | DragEvent |
dragstart | The event occurs when the user starts to drag an element | DragEvent |
drop | The event occurs when the dragged element is dropped on the drop target | DragEvent |
durationchange | The event occurs when the duration of the media is changed | Event |
ended | The event occurs when the media has reach the end (useful for messages like "thanks for listening") | Event |
error | The event occurs when an error occurs while loading an external file | ProgressEvent, UiEvent, Event |
focus | The event occurs when an element gets focus | FocusEvent |
focusin | The event occurs when an element is about to get focus | FocusEvent |
focusout | The event occurs when an element is about to lose focus | FocusEvent |
fullscreenchange | The event occurs when an element is displayed in fullscreen mode | Event |
fullscreenerror | The event occurs when an element can not be displayed in fullscreen mode | Event |
hashchange | The event occurs when there has been changes to the anchor part of a URL | HashChangeEvent |
input | The event occurs when an element gets user input | InputEvent, Event |
invalid | The event occurs when an element is invalid | Event |
keydown | The event occurs when the user is pressing a key | KeyboardEvent |
keypress | The event occurs when the user presses a key | KeyboardEvent |
keyup | The event occurs when the user releases a key | KeyboardEvent |
load | The event occurs when an object has loaded | UiEvent, Event |
loadeddata | The event occurs when media data is loaded | Event |
loadedmetadata | The event occurs when meta data (like dimensions and duration) are loaded | Event |
loadstart | The event occurs when the browser starts looking for the specified media | ProgressEvent |
message | The event occurs when a message is received through the event source | Event |
mousedown | The event occurs when the user presses a mouse button over an element | MouseEvent |
mouseenter | The event occurs when the pointer is moved onto an element | MouseEvent |
mouseleave | The event occurs when the pointer is moved out of an element | MouseEvent |
mousemove | The event occurs when the pointer is moving while it is over an element | MouseEvent |
mouseover | The event occurs when the pointer is moved onto an element, or onto one of its children | MouseEvent |
mouseout | The event occurs when a user moves the mouse pointer out of an element, or out of one of its children | MouseEvent |
mouseup | The event occurs when a user releases a mouse button over an element | MouseEvent |
mousewheel | Deprecated. Use the wheel event instead | WheelEvent |
offline | The event occurs when the browser starts to work offline | Event |
online | The event occurs when the browser starts to work online | Event |
open | The event occurs when a connection with the event source is opened | Event |
pagehide | The event occurs when the user navigates away from a webpage | PageTransitionEvent |
pageshow | The event occurs when the user navigates to a webpage | PageTransitionEvent |
paste | The event occurs when the user pastes some content in an element | ClipboardEvent |
pause | The event occurs when the media is paused either by the user or programmatically | Event |
play | The event occurs when the media has been started or is no longer paused | Event |
playing | The event occurs when the media is playing after having been paused or stopped for buffering | Event |
popstate | The event occurs when the window's history changes | PopStateEvent |
progress | The event occurs when the browser is in the process of getting the media data (downloading the media) | Event |
ratechange | The event occurs when the playing speed of the media is changed | Event |
resize | The event occurs when the document view is resized | UiEvent, Event |
reset | The event occurs when a form is reset | Event |
scroll | The event occurs when an element's scrollbar is being scrolled | UiEvent, Event |
search | The event occurs when the user writes something in a search field (for <input="search">) | Event |
seeked | The event occurs when the user is finished moving/skipping to a new position in the media | Event |
seeking | The event occurs when the user starts moving/skipping to a new position in the media | Event |
select | The event occurs after the user selects some text (for <input> and <textarea>) | UiEvent, Event |
show | The event occurs when a <menu> element is shown as a context menu | Event |
stalled | The event occurs when the browser is trying to get media data, but data is not available | Event |
storage | The event occurs when a Web Storage area is updated | StorageEvent |
submit | The event occurs when a form is submitted | Event |
suspend | The event occurs when the browser is intentionally not getting media data | Event |
timeupdate | The event occurs when the playing position has changed (like when the user fast forwards to a different point in the media) | Event |
toggle | The event occurs when the user opens or closes the <details> element | Event |
touchcancel | The event occurs when the touch is interrupted | TouchEvent |
touchend | The event occurs when a finger is removed from a touch screen | TouchEvent |
touchmove | The event occurs when a finger is dragged across the screen | TouchEvent |
touchstart | The event occurs when a finger is placed on a touch screen | TouchEvent |
transitionend | The event occurs when a CSS transition has completed | TransitionEvent |
unload | The event occurs once a page has unloaded (for <body>) | UiEvent, Event |
volumechange | The event occurs when the volume of the media has changed (includes setting the volume to "mute") | Event |
waiting | The event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data) | Event |
wheel | The event occurs when the mouse wheel rolls up or down over an element | WheelEvent |
HTML DOM Event Properties and Methods
Property/MethodDescriptionBelongs To
이벤트 | 설명 | 구분 | |
altKey | Returns whether the "ALT" key was pressed when the mouse event was triggered | MouseEvent | |
altKey | Returns whether the "ALT" key was pressed when the key event was triggered | KeyboardEvent, TouchEvent | |
animationName | Returns the name of the animation | AnimationEvent | |
bubbles | Returns whether or not a specific event is a bubbling event | Event | |
button | Returns which mouse button was pressed when the mouse event was triggered | MouseEvent | |
buttons | Returns which mouse buttons were pressed when the mouse event was triggered | MouseEvent | |
cancelable | Returns whether or not an event can have its default action prevented | Event | |
charCode | Returns the Unicode character code of the key that triggered the onkeypress event | KeyboardEvent | |
changeTouches | Returns a list of all the touch objects whose state changed between the previous touch and this touch | TouchEvent | |
clientX | Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered | MouseEvent, TouchEvent | |
clientY | Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered | MouseEvent, TouchEvent | |
clipboardData | Returns an object containing the data affected by the clipboard operation | ClipboardData | |
code | Returns the code of the key that triggered the event | KeyboardEvent | |
composed | Returns whether the event is composed or not | Event | |
ctrlKey | Returns whether the "CTRL" key was pressed when the mouse event was triggered | MouseEvent | |
ctrlKey | Returns whether the "CTRL" key was pressed when the key event was triggered | KeyboardEvent, TouchEvent | |
currentTarget | Returns the element whose event listeners triggered the event | Event | |
data | Returns the inserted characters | InputEvent | |
dataTransfer | Returns an object containing the data being dragged/dropped, or inserted/deleted | DragEvent, InputEvent | |
defaultPrevented | Returns whether or not the preventDefault() method was called for the event | Event | |
deltaX | Returns the horizontal scroll amount of a mouse wheel (x-axis) | WheelEvent | |
deltaY | Returns the vertical scroll amount of a mouse wheel (y-axis) | WheelEvent | |
deltaZ | Returns the scroll amount of a mouse wheel for the z-axis | WheelEvent | |
deltaMode | Returns a number that represents the unit of measurements for delta values (pixels, lines or pages) | WheelEvent | |
detail | Returns a number that indicates how many times the mouse was clicked | UiEvent | |
elapsedTime | Returns the number of seconds an animation has been running | AnimationEvent | |
elapsedTime | Returns the number of seconds a transition has been running | ||
eventPhase | Returns which phase of the event flow is currently being evaluated | Event | |
getTargetRanges() | Returns an array containing target ranges that will be affected by the insertion/deletion | InputEvent | |
getModifierState() | Returns an array containing target ranges that will be affected by the insertion/deletion | MouseEvent | |
inputType | Returns the type of the change (i.e "inserting" or "deleting") | InputEvent | |
isComposing | Returns whether the state of the event is composing or not | InputEvent, KeyboardEvent | |
isTrusted | Returns whether or not an event is trusted | Event | |
key | Returns the key value of the key represented by the event | KeyboardEvent | |
key | Returns the key of the changed storage item | StorageEvent | |
keyCode | Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event | KeyboardEvent | |
location | Returns the location of a key on the keyboard or device | KeyboardEvent | |
lengthComputable | Returns whether the length of the progress can be computable or not | ProgressEvent | |
loaded | Returns how much work has been loaded | ProgressEvent | |
metaKey | Returns whether the "META" key was pressed when an event was triggered | MouseEvent | |
metaKey | Returns whether the "meta" key was pressed when the key event was triggered | KeyboardEvent, TouchEvent | |
MovementX | Returns the horizontal coordinate of the mouse pointer relative to the position of the last mousemove event | MouseEvent | |
MovementY | Returns the vertical coordinate of the mouse pointer relative to the position of the last mousemove event | MouseEvent | |
newValue | Returns the new value of the changed storage item | StorageEvent | |
newURL | Returns the URL of the document, after the hash has been changed | HasChangeEvent | |
offsetX | Returns the horizontal coordinate of the mouse pointer relative to the position of the edge of the target element | MouseEvent | |
offsetY | Returns the vertical coordinate of the mouse pointer relative to the position of the edge of the target element | MouseEvent | |
oldValue | Returns the old value of the changed storage item | StorageEvent | |
oldURL | Returns the URL of the document, before the hash was changed | HasChangeEvent | |
onemptied | The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects) | ||
pageX | Returns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggered | MouseEvent | |
pageY | Returns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggered | MouseEvent | |
persisted | Returns whether the webpage was cached by the browser | PageTransitionEvent | |
preventDefault() | Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur | Event | |
propertyName | Returns the name of the CSS property associated with the animation or transition | AnimationEvent, TransitionEvent | |
pseudoElement | Returns the name of the pseudo-element of the animation or transition | AnimationEvent, TransitionEvent | |
region | MouseEvent | ||
relatedTarget | Returns the element related to the element that triggered the mouse event | MouseEvent | |
relatedTarget | Returns the element related to the element that triggered the event | FocusEvent | |
repeat | Returns whether a key is being hold down repeatedly, or not | KeyboardEvent | |
screenX | Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered | MouseEvent | |
screenY | Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered | MouseEvent | |
shiftKey | Returns whether the "SHIFT" key was pressed when an event was triggered | MouseEvent | |
shiftKey | Returns whether the "SHIFT" key was pressed when the key event was triggered | KeyboardEvent, TouchEvent | |
state | Returns an object containing a copy of the history entries | PopStateEvent | |
stopImmediatePropagation() | Prevents other listeners of the same event from being called | Event | |
stopPropagation() | Prevents further propagation of an event during event flow | Event | |
storageArea | Returns an object representing the affected storage object | StorageEvent | |
target | Returns the element that triggered the event | Event | |
targetTouches | Returns a list of all the touch objects that are in contact with the surface and where the touchstart event occured on the same target element as the current target element | TouchEvent | |
timeStamp | Returns the time (in milliseconds relative to the epoch) at which the event was created | Event | |
total | Returns the total amount of work that will be loaded | ProgressEvent | |
touches | Returns a list of all the touch objects that are currently in contact with the surface | TouchEvent | |
transitionend | The event occurs when a CSS transition has completed | TransitionEvent | |
type | Returns the name of the event | Event | |
url | Returns the URL of the changed item's document | StorageEvent | |
which | Returns which mouse button was pressed when the mouse event was triggered | MouseEvent | |
which | Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event | KeyboardEvent | |
view | Returns a reference to the Window object where the event occurred | UiEvent |
Other Event Objects
These are the most common event objects:
Event Object | Description |
AnimationEvent | For CSS animations |
ClipboardEvent | For modification of the clipboard |
DragEvent | For drag and drop interaction |
FocusEvent | For focus-related events |
HashChangeEvent | For changes in the anchor part of the URL |
InputEvent | For user input |
KeyboardEvent | For keyboard interaction |
MouseEvent | For mouse interaction |
PageTransitionEvent | For navigating to, and away from, web pages |
PopStateEvent | For changes in the history entry |
ProgressEvent | For the progress of loading external resources |
StorageEvent | For changes in the window's storage area. |
TouchEvent | For touch interaction |
TransitionEvent | For CSS transitions |
UiEvent | For user interface interaction |
WheelEvent | For mousewheel interaction |
이벤트 위임(Delegation)이란?
사용자의 액션에 의해 이벤트 발생 시,이벤트는 document 레벨까지 버블링 되어 올라가는데 이로 인해 자식 엘리먼트에서 발생하는 이벤트를 부모 엘리먼트에서도 감지할 수 있다. 이를 활용하는 것이 이벤트 위임이다.
특정 엘리먼트에 하나하나 이벤트를 등록하지 않고 하나의 부모에 등록하여 부모에게 이벤트를 위임하는 방법이다.
(자식 노드에 일일이 이벤트를 등록하지 않아도, 자식 요소로 이벤트를 실행가능하게 함)
이벤트 위임의 장점, Delegation 해야하는 이유
- 동일한 이벤트에 대해 한 곳에서 관리하기 때문에(각각의 엘리먼트를 여러 곳에 등록하여 관리하는 것보다)관리가 수월하다.
- 동적인 element의 event 처리에 용이하다.
- 상위 element에서만 event Listener를 관리하기 때문에 하위 element 추가, 삭제가 자유롭다.
- event handler 추가 제거 등의 관리가 쉽다.
※ (event.target.)tagName은 모든 DOM 객체가 가진 property이므로, 항상 대문자를 사용한다.
참고,
tagName이 대문자로 태그이름을 가지고 있기 때문에
소문자로 바꾸려면 (string.prototype.)toLowerCase() 메서드를 사용하면 된다.
event.target.tagName.toLowerCase()
- 위 메서드는 호출 문자열을 소문자로 변환해서 반환한다.
- 기존의 string에 영향을 주지 않는다.
※ 리턴(return)의 쓰임과 이유에 대해
- 해당 결과 값을 함수 호출 지점으로 반환(return) 한다.
- 요건 충족시 함수를 중단하고 돌아나가는 기능.
추가로 궁금했던 것은,
그 외 반환값이 없을 때 return을 하는 이유인데
이는 'window 객체'에 event listener를 부여하기 때문이다.
ul 객체에 어떠한 event를 달면 굳이 ul인지 비교할 필요가 없지만
window 객체의 모든 하위 DOM 객체들에게서 이벤트가 발생하기 때문에
ul 객체 구분을 위해 조건문을 사용하고 리턴한다.
(HTML내 footer_input class가 있다고 가정)
const input = document.querySelector('.footer_input');
const text = input.value;
if (text === '') {
return;
}
※ 사용자가 아무것도 입력을 안 했을 때 리턴하여 그대로 함수를 나간다.
= 아무일도 아무일도 일어나지 않음.
즉, 원하는 목적이 아니라면 바로 리턴하여 아무일도 하지 않기 위해 사용한다.
'개발자정보' 카테고리의 다른 글
웹 개발자 drag & drop (0) | 2022.06.12 |
---|---|
웹 개발자 알아두면 쓸데없는 지식 (0) | 2022.06.12 |
웹 개발자 CSS 정리 (0) | 2022.06.11 |
웹 개발자 HTML 태그 정리 (0) | 2022.06.10 |
자바 Threads를 활용한 병렬처리 (0) | 2022.06.04 |