써치킴의 우당탕탕 개발 블로그

[JavaScript][Ch9] JS 함수 본문

파도파도 나오는 JavaScript

[JavaScript][Ch9] JS 함수

써치킴 2022. 1. 6. 06:47

함수

특정 동작(기능)을 수행하는 일부 코드의 집합(부분)

function

// 함수 선언
function helloFunc() {
  // 실행 코드
  console.log(1234);
}

// 함수 호출
helloFunc();    // 1234

 

함수 안에서 특정값을 반환할 수 있다. -> return 사용

function returnFunc() {
  return 123;   // 123을 반환해줌
}

let a = returnFunc();

console.log(a);   // 123

 

매개변수와 인수

function sum(a, b) {    // a, b는 매개변수(Parameters)
  return a + b;
}

// 재사용
let a = sum(1, 2);      // 1, 2는 인수(Arguments)
let b = sum(7, 12);
let c = sum(2, 4);

console.log(a, b, c);   // 3, 19, 6

 

기명함수와 익명함수

// 기명(이름이 있는) 함수 -> 함수를 선언한다고 함!
function hello() {
  console.log('hello');
}

// 익명(이름이 없는) 함수 -> 함수를 표헌한다고 함!
// 익명함수는 데이터로써 활용, 변수를 이용해서 사용
let world = function () {
  console.log('world');
}

// 함수 호출
hello();
world();

 

객체 데이터

// 객체 데이터
const searchkim = {
  name: 'SEARCHKIM',
  age: 85,
  // getName에 익명함수가 데이터로써 들어가있음(함수의 표현)
  // 속성에 함수가 할당되어 있으면 메소드라고 함
  getName: function () {    // 메소드(Method)
    return this.name;
  }
};

const name = searchkim.getName();
console.log(name);    // SEARCHKIM

console.log(searchkim.getName());   // SEARCHKIM
Comments