LoginSignup
0
0

More than 1 year has passed since last update.

独習JavaScript(6章 関数)

Last updated at Posted at 2022-08-07

独習JavaScriptのメモ

本はこちら

はじめに

  • 今までJavaScriptは、ほぼ雰囲気で使っていた。が、ごまかしがきかなくなってきた。
  • ので、(必要に迫られて)本書を手に取った。当初は基礎を総点検するのが目的だった。
  • やり始めると知らなこと、理解が曖昧なモノが思いのほか多かった。なのでメモとして残す。
  • 実務では利用しなさそうなモノもありそう。だが知識として残す。

6章 関数

argumentsオブジェクト

引数は関数内でのみ利用できるargmentsというオブジェクトに格納される。
ただ使わないと思うし使われているのを見たことも無い。知識として。

argument.js
function f_sum() { // 引数の定義なし
    return arguments[0] + arguments[1];
}

console.log(f_sum(2,3));
// ----> 5

関数宣言より前で関数の実行を記述できる。

言われてみればそうだけど、改めて見てみると気持ち悪い。

function_call.js
console.log(f_sum(2,3)); // 関数実行文
// ----> 5

function f_sum(foo, bar) { // 関数定義
    return foo + bar;
}

関数定義で引数のdefault値が書ける。

仮引数がundefindedの場合にdefault値が設定される。
これもあまり利用シーンは無いのかも。

default.js
function calc(foo, tax=8) { // 引数の定義なし
    return foo +(foo * (tax/100));
}

console.log(calc(100)); // taxを省略
// ----> 108

console.log(calc(100,undefined)); // 明示的にundefinedしても同じ
// ----> 108

console.log(calc(100,10)); // 記載すればその値が使われる
// ----> 110

console.log(calc(100,null)); // nullは0に変換されるらしい
// ----> 100

ちなみにNull合体の自己代入でも似た実装が実装できる。

default.js
function calc(foo, tax) { // 引数の定義なし
    tax ??= 8; // 引数taxがNull,undefinedの場合は8を設定する。
    return foo +(foo * (tax/100));
}

console.log(calc(100)); // taxを省略
// ----> 108

console.log(calc(100,undefined)); // 明示的にundefinedしても同じ
// ----> 108

console.log(calc(100,10)); // 記載すればその値が使われる
// ----> 110

console.log(calc(100,null)); // tax ??= 8によって8で計算される。
// ----> 100

コールバック関数

他の関数の引数に渡す関数。

callback.js
function stopwatch(seconds) {
    alert(seconds + "秒経過しました。");
}

setTimeout(stopwatch,5000,5);
// ----> 5秒経過しました。

無名関数

コールバック関数は大体無名関数で定義する。対して名前の有る関数を『名前付き関数』と呼ぶ。

anonymous.js
setTimeout(function(seconds) { // <---関数名は定義なし
    alert(seconds + "秒経過しました。")
    },5000,5);
// ----> 5秒経過しました。

const fn1 = function(seconds) {alert(seconds + "秒経過しました。")}
// > 関数を変数fn1に代入
setTimeout(fn1,5000,5);
// > fn1をコールバック関数として引数に設定 
// ----> 5秒経過しました。(同じ結果)

アロー関数

アロー関数は『無名関数』の省略記法。
引数は『()』、処理は『{}』で記載し『=>』でつなげる。

arrow.js
const arrow = () => { 処理; }

ちなみに色々省略で書ける。

arrow.js
// 引数が一つの場合は『()』が省略できる。
const arrow = arg1 => { 処理; }

// 処理(関数の本文)が1文の場合は『{}』と『return』が省略できる。
const arrow = () => 処理;
// 処理が戻り値になる。

// 戻り値がオブジェクトの場合
const arrow = () => {return ({one:1, two:2, three:3})} // オブジェクトは『()』で括る。
console.log(f());
// -----> {"one": 1,"two": 2,"three": 3}

const arrow = () => ({one:1, two:2, three:3}) // 同様に処理が1文の場合は『{}』を省略できる。
console.log(f());
// -----> {"one": 1,"two": 2,"three": 3}

無名関数とアロー関数は挙動が異なる。

(今の段階では)基本はアロー関数で書いとけ、と思ってよさそう。

キーワード 無名関数 アロー関数
this thisを持つ thisを持たない
arguments argumentsを持つ argumentsを持たない
new インスタンス化が可能 インスタンス化が不可
prototype prototypeを持つ prototypeを持たない
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