LoginSignup
230
142

More than 5 years have passed since last update.

Cannot read property 'fuga' of undefined とは

Last updated at Posted at 2016-07-27

エラーの内容について、ちゃんと意味を理解できていなかったので書いてみる。
今プロジェクトでjsを使っているのだが、その際に表題のような
Cannot read property 'fuga' of undefined
というエラーが出たりする。
これが出た時に、
「fugaがundefinedなんですね!」
というと
「fuck」
という顔をされてしまい、説明をいただきました。
英語の問題ですね。

問題は
「'fuga' of undefined」
意味は「undefined の 'fuga'」

fuga がundedinedなんじゃなくて、
「undefinedにある'fuga'property(名前付きの値)は読み込めません。」
という意味になる。
ということはfugaの前のオブジェクトがundefinedだということ。

今回は
hoge = undefined
hoge.fuga()
とすると上記のエラーが出た。つまりhogeがundefinedだったのだ。

なのでこういうエラーが出た時にエラーチェックをしようとしたければ

if (hoge)
  hoge.fuga()
else
 ...

とすると、hogeがundefindedのときにきちんと分岐してくれる。

勉強になった。

230
142
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
230
142