function hello() {
// 함수 선언문
}
const hello = function () {
// 함수 표현식
}
return 키워드가 없으면 undefined를 자동으로 반환 (무시 가능)
function hello(a, b = 1) {
return a + b
}
sum(7) // 7 + 1 = 8
const user = {
name: 'gaji',
city: 'busan'
}
function getName(user) {
const { name } = user
return name
}
function getName({ name }) {
return name
}
console.log(getName(user)) // gaji
function getMail({ email = '이메일이 없습니다' }) {
return email
}
numbers = [1, 2, 3]
function getSecond([, b]) {
return b
}
console.log(getSecond(numbers)) // 2
// 배열 속 요소의 합 구하기
function sum(...rest) {
return rest.reduce(function (acc, cur) {
return acc + cur
}, 0)
}
// reduce : 콜백함수
// rest.reduce : rest 요소 개수만큼 콜백함수를 실행
// acc : 누적되는 값 (시작값 0으로 지정)
// cur : 현재 값 (요소의 값)
function sum(...rest) {
console.log(arguments)
}
const funcName = () => {}
return 생략 가능const a = (x,y) => {return x + y}
const b = (x,y) => x + y
// return 생략
const c = x => x * x
// 매개변수가 1개 : 소괄호 생략
const d = () => ({a: 1})
// 객체 데이터 반환 시 소괄호를 사용하여 함수 블록이 아닌 객체 데이터임을 구분
const d = () => [1,2,3]
// 배열 데이터 반환
정의되자마자 즉시 실행되는 함수
// 세미콜론을 앞에 붙여주기
;(() => {})() // (F)()
;(function () {})() // (F)()
;(function () {}()) // (F())
;!function () {}() // !F()
;+function () {}() // +F()
;((a, b) => {
console.log(a.innerWidth)
console.log(b.body)
})(window, document) // 코드의 난독화
// 1을 출력하는 함수 바로 다음 2를 출력하는 함수를 실행하고 싶을 때
const first = (파라미터) => {
console.log(1)
파라미터()
}
const second = () => {
console.log(2)
}
first(second)
longWords = words.filter(element => element.length > 6)
consloe.log(longWords)
// true 또는 false를 리턴하는 익명함수가 콜백함수로 사용됨
// callback (element) => {return element.length > 6}
https://www.youtube.com/watch?v=TAyLeIj1hMc
const sum = (a, b, callback) => {
setTimeout(() => {callback(a + b)}, 1000)
// console.log(값)를 실행시키라는거
}
sum(1, 2, (value) => {console.log(value)})
// (value) => {console.log(value)} 익명함수가 3번째 매개변수callback 으로 들어감
const loadImage = (url, callback) => {
const imgEl = document.createElement('img')
// img 태그를 생성하는 함수
imgEl.src = url
// img 태그의 src 속성에 url을 할당
imgEl.addEventListener('load', () => {
// load : html 문서를 완전히 불러왔을 때 이벤트 발생
// load 이벤트가 발생하면 callback함수를 실행함
callback(imgEl)
})
}
loadImage('https://url', imgEl => {
containerEl.innerHTML = ''
containerEl.append(imgEl)
})
setTimeout 함수 : 특정 함수의 실행을 지연시키는 메서드setTimeout(callback, t) : callback 함수를 t ms 이후에 실행 const hello = () => {
console.log('hello')
}
setTimeout(hello, 2000)
clearTimeout : setTimeout을 취소시키는 메서드const timeout = setTimeout(hello, 2000)
clearTimeout(timeout)
h1 요소를 클릭했을 때 타이머 초기화
const timeout = setTimeout(hello, 2000)
const h1El = document.querySelector('h1')
// click 이벤트가 발생한다면 콜백함수를 실행
h1El.addEventListener('click', () => {
// hello 함수가 실행되기 전이라면, 실행되지 않도록 함
clearTimeout(timeout)
})
setInterval(callback, t) : t밀리초 마다 callback 함수를 실행
clearInterval : setInterval 반복 실행을 종료시키는 메서드
https://developer-talk.tistory.com/534
const object = {
show1: function() {
console.log('메서드 호출')
}
}
show2() => {
console.log('함수 호출')
}
object.show1() // 메서드 (객체를 통해 호출함)
show2() // 함수
window.show2() // 전역 객체를 통해 호출 가능
(출처 : https://nykim.work/71)
함수는 Window 객체의 property 이므로,
this는 Window 객체를 가리킴
const user = () => {
return this
}
console.log(user()) // Window 객체 출력
var num = 0;
function Num() {
this.num = 100;
console.log(num) // 100
console.log(this.num) // 100
console.log(window.num) // 100
}
// num은 전역 변수를 가리키게 됨
const user = {
firstName: 'local',
lastName: 'gaji',
fullName: function() {
return `${this.firstName} ${this.lastName}`
// this 가 user 객체를 가리킴
}
}
user.fullName() // local gaji
메서드에서 this는 해당 메서드를 호출한 객체를 가리킴
const btn = document.querySelector('#btn')
// 버튼 찾기
btn.addEventListener('click', function() {
console.log(this) // #btn
}
this 는 이벤트를 받는 HTML 요소를 가리킴
화살표 함수에서는 this를 새로 정의하지 않고, 바깥 함수의 this를 사용
const timer = {
title: "TIMER",
timeout: function () {
console.log(this.title) // this = timer 객체
setTimeout(function () {
console.log(this.title) // this = window 객체
}, 100)
}
}
timer.timeout() // TIMER undefined
setTimeout은 일반함수이므로 this.title는 window.title (undefined)
const timer = {
title: "TIMER",
timeout: function () {
console.log(this.title) // this = timer 객체
setTimeout( () => {
console.log(this.title) // this = timer 객체
}, 100)
}
}
timer.timeout() // TIMER TIMER
setTimeout이 화살표함수이므로 바깥함수의 this인 timer 객체를 가리킴