2
0

More than 3 years have passed since last update.

Javascriptレシピ①

Last updated at Posted at 2019-12-18

Javascriptの簡単なメモです。
アプリ制作に応用できる基本レシピですので、参考にされたい方はどうぞ。

関数の書き方

①関数宣言

function wanko(){
         }

wankoという関数名をつけて関数宣言しています。
おなじみですね。

②関数式

const wanko = function(){
      }

const wanko = () => {
      }

無名関数というやつです。
関数はデータの方として存在しているのでこのような書き方が可能になります。

Functionオブジェクトのオンストラクタを使った書き方もあるのですが、ほぼ間違いなく使わないので省略します。

書き方

const p = document.createElement('p');
p.textContent = 'wanko';
documen.body.appendChild(p);

これを関数にすると


function toypoo(){
    const p = document.createElement('p');
    p.textContent = 'wanko';
    documen.body.appendChild(p);
}

コード自体はdocument.createElment(p)でp要素を作成
p要素のtextContentをwankoに
bodyにp要素を付与しています。

toypooという関数が出来ましたね、toypoo();で呼び出せます。

ボタン
このように書くとボタンを押したらtoypoo関数が呼び出されます。

HTMLファイルが読み込まれたらwankoと表示します。


window.onload = function(){
    console.log('wanko');
}

window.addEventListner('load', function(){
    console.log('wanko');
})

引数

Javascriptでは引数を複数指定できます。

function wanko(pome,toypoo){

    }

//引数にpomeとtoypooを指定することで関数内でpomeとtoypooが使えるようになります。

wanko(1,2);

//それぞれpomeとtoypooに対応しています。

引数にコールバック関数

function wanko(callback){
    setTimeout(function(){
        console.log('wanko');
        callback();
    }, 2000)
}

引数にcallback関数を指定しているので2秒経過後に引数に指定した関数が実行されます。

returnで返り値

function wanko(toypoo, pome){

    return toypoo+pome;
}

if(wanko(7,5) > 3){

 console.log('wan');
}  else {
       console.log(wanwan);
}

returnで返り値を戻すことで普通の値として関数を使えるようになりました。

続く

2
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
2
0