LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】モジュール③ モジュールコンテキストとモジュールスコープ

Posted at

はじめに

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

前回の記事

目的

  • モジュールについての理解を深める

本題

1.モジュールコンテキスト

モジュールコンテキストではthisが使えない

moduleB.js
// thisを出力してもundefinedと出力される
console.log(this);
// 関数でも同様
function fn(){
  console.log(this);
}
// moduleを使わない場合にはwindowオブジェクトが取れていた
fn();
module.js
function fn(){
  console.log(this);
}
fn();
// objの中に格納した場合
const obj = {
  fn
}
// fnはobjのメソッドとして使える
obj.fn();
// 呼び出し元のobjのことを参照する

2.モジュールスコープ

moduleA.js, moduleB.jsを用意
基本的にはそれぞれで使う変数や関数はそれぞれのファイル内だけで使用できる

外部の変数や関数を使う場合はimportやexportで明示的に宣言する必要がある

moduleA.js
const a = 0

moduleAで上記のように宣言しても, moduleB.jsに持ってこれない(importしない限り)

moudleB.js
// 関数外で変数を宣言
const a = 0
function fn(){
  console.log(this);
  // レキシカルスコープは使用可能
  console.log(a);
}
fn();

const obj = {
  fn
}
obj.fn();

グローバルスコープも使用可能

moduleA.js
// window.bに1を代入
window.b = 1
moduleB.js
// moduleA.jsで宣言された変数を使用するために読み込む
import "./moduleA.js"
// 以下で1と出力される
console.log(window.b);
// fromを書かなくてもmoduleAを実行するだけなのでOK

今日はここまで!

参考にさせて頂いた記事

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