0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[JS] コールバック関数

Last updated at Posted at 2021-03-25

callback関数

関数を渡すことによって、その関数を受け取った側の関数内で実行することができる

function hello(callback) {
  console.log('hello' + callback);
}

function getName() {
  return 'Shun';
}

hello(getName);

Image from Gyazo

これはどうなっているかというと

function hello(getName) {
  console.log('hello' + 'Shun');
}

function getName() {
  return 'Shun';
}

hello(getName);

まず最初のhelloの引数callbackにgetNameが入ります
次に2行目の+ callbackが+ 'Shun'に置換されます
そして結果は一緒です


関数として取り扱う

function hello(callback) {
  console.log(callback);
}

function getName() {
  return 'Shun';
}

function getFirstName() {
  return 'Sato';
}

hello(getFirstName);

Image from Gyazo


変数として取り扱う

function hello(callback) {
  console.log(callback);
}

function getName() {
  return 'Shun';
}

const getFirstName = function () {
  return 'Sato';
}

hello(getFirstName);

Image from Gyazo


無名関数をそのままcallback関数として渡す

function hello(callback) {
  console.log(callback);
}

function getName() {
  return 'Shun';
}

hello(function () {
  return 'Sato';
});

Image from Gyazo


アロー関数をcallback関数として渡す

function hello(callback) {
  console.log(callback);
  console.log('hello' + callback());
}

function getName() {
  return 'Shun';
}

hello(() => 'Sato');

Image from Gyazo


引数2つ

function hello(callback, lastname) {
  console.log(callback);
  console.log('hello' + callback(lastname));
}

function getName() {
  return 'Shun';
}

hello(function(name) {
  return 'Sato' + name;
}, 'Shun');

無名関数をcallback関数として渡しています
引数nameはどこから来てるか? lastnameの値が入ります

Image from Gyazo


計算

function doSomething(a, b, callback) {
  const result = callback(a, b);
  console.log(result);
}

function multiply(a, b) {
  return a * b;
}

function plus(a, b) {
  return a + b;
}

doSomething(3, 4, multiply); 
doSomething(11, 4, plus); 

Image from Gyazo

ループ処理

const arry = [1,2,3,4,5];

function forEach(ary, callback) {
  for(let i = 0; i < ary.length; i++) {
    callback(ary[i]);
  }
}

function log(val) {
  console.log(val);
}

forEach(arry, log);

Image from Gyazo


const arry = [1,2,3,4,5];

function forEach(ary, callback) {
  for(let i = 0; i < ary.length; i++) {
    callback(ary[i]);
  }
}

function log(val) {
  console.log(val);
}

function double(val) {
  val = val * 2;
  log(val);
}

forEach(arry, double);

Image from Gyazo

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?