LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】関数とオブジェクト⑤ bindとthis

Last updated at Posted at 2021-10-19

はじめに

Udemyの【JS】ガチで学びたい人のためのJavaScriptメカニズムの講座の振り返りです。

前回の記事

目的

  • 関数とオブジェクトについての理解を深める

本題

1.前回のおさらい

window.name = 'John';

const person = {
    name: 'Tom',
    hello: function() {
        console.log('Hello ' + this.name);
    }
}

person.hello();


function fn(ref){
    ref();
}
// personのhelloメソッドをコールバック関数として渡した際に
// refを実行した際のthisのオブジェクト先がwindowオブジェクトになった
fn(person.hello); 

// personのhelloの参照先がrefに格納されているためrefでは関数が実行されているとみなされる
// => グローバルオブジェクトを参照する

2.bind

this引数を固定した新しい関数を作成できる。
=> bindによるthisの束縛

例1

上記のrefの実行により,Hello Tomを出力するにはどうすればいいのか

window.name = 'John';

const person = {
    name: 'Tom',
    hello: function() {
        console.log('Hello ' + this.name);
    }
}

// 変数helloTomを定義する
// bindの第一引数で渡したオブジェクト(person)を
// helloの中で実行されるthisの参照先として設定し,
// その設定をhelloTomに入れる
const helloTom = person.hello.bind(person);
// 第一引数で指定したオブジェクトをthisの参照先に限定、縛る

function fn(ref){
    ref();
}
// コールバック関数として実行
fn(helloTom);

例2

より簡単な例

const person = {
    name: 'Tom',
    hello: function() {
        console.log('Hello ' + this.name);
    }
}

function a(){
    console.log("hello " + this.name);
}
// bindの第一引数をaのオブジェクト内のthisに限定し、bに返却
const b = a.bind({name: "太郎"});
// これもいけた
const c = a.bind(person);
// 実行
b();
c();

例3

bindではthisだけでなく引数も固定することができる

const person = {
    name: 'Tom',
    hello: function() {
        console.log('Hello ' + this.name);
    }
}
// 引数にnameを入れる(中身のthisを削除した)
function a(name){
    console.log("hello " + name);
}
// 関数内でthisが使用されていないので,第一引数は必要ない => nullとしておく
// 第2引数として関数の引数を渡すことでbindをかけられる
const b = a.bind(null, "次郎");
// 「hello 次郎」と出力
b();
// もし、bに引数を渡したとしてもbindが優先される
b("三郎");
実行結果.
hello 次郎
hello 次郎

今日はここまで!

参考にさせて頂いた記事

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