Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

【Javascript】thisを用いたときにresultだけ出力される

解決したいこと

関数をコールするときのthisの挙動について
パターン1 関数を代入してから呼び出す→this以下がresultで出力されてしまう
パターン2 関数をそのまま呼び出す→this以下が通常で出力

発生している問題・エラー

パターン1 関数を代入してから呼び出す
let obj = {
  name:"TOM",
  hello:function(){
    console.log(`こんにちは${this.name}さん`)
    console.log(`${obj.name}さん元気ですか?`)
  }
}
let question = obj.hello;
question()

スクリーンショット 2022-10-04 17.04.50.png

例)

パターン2 関数をそのまま呼び出す
let name = "tani"
let obj = {
  name:"TOM",
  hello:function(){
    console.log(`こんにちは${this.name}さん`)
    console.log(`${obj.name}さん元気ですか?`)
  }
}
obj.hello()

スクリーンショット 2022-10-04 16.40.20.png

確認したいこと

なぜthisを用いたときにresultだけ出力されるのかが知りたいです。よろしくお願いします。

0

1Answer

私のNode.js環境では

こんにちはundefinedさん
TOMさん元気ですか?

になりましたよ。

obj.hello() では、objthis にバインドされます。
question() では、this がバインドされず、thisはグローバルオブジェクトだったりします。
questionthisobj をバインドしたければ、

question.call(obj)
question.bind(obj)()

などとして呼び出す必要があります。
あるいは、

let question = obj.hello.bind(obj);
question()

でもいけます。
最近は、アロー関数で書きます。

let question = () => obj.hello();
question()
0Like

Comments

  1. @gucho-n

    Questioner

    ありがとうございます!非常にわかりやすく助かりました

Your answer might help someone💌