Salesforce 認定 JavaScript デベロッパー 無料問題 9 / 10 ・ 分野6: サーバーサイド JavaScript
CommonJS モジュールが、exports に新しいオブジェクトを直接代入し、そのあと module.exports を出力する。 exports = { greet() { return 'hi'; } }; console.log(module.exports); 何が出力されるか。
- { greet: [Function: greet] } になる。require は、exports に最後に代入された値を読むため
- {} になる。exports は、require が返す module.exports にもう束縛されていないため
- undefined になる。module.exports を使わないモジュールには、エクスポートのオブジェクトが無いため
- { greet: [Function: greet] } になる。exports と module.exports は同じ変数であるため
正解と解説を見る
正解: B
正解の理由
exports 変数には、モジュールが評価される前に module.exports の値が代入されるので、exports.f = ... は module.exports.f = ... の近道として働く。ここのように exports に新しい値を代入すると、変数が再束縛されるだけで、module.exports は空のオブジェクトのままになり、それが出力され、require が返すものになる。
違う選択肢
「{ greet: [Function: greet] } になる。exports と module.exports は同じ変数であるため」… exports は、module.exports の値で始まる変数である。新しい値を代入したあとは、module.exports に束縛されていない。
「undefined になる。module.exports を使わないモジュールには、エクスポートのオブジェクトが無いため」… module.exports はどのモジュールにも存在し、空のオブジェクトで始まる。再束縛されるのは exports であり、module.exports ではない。
「{ greet: [Function: greet] } になる。require は、exports に最後に代入された値を読むため」… require が返すのは module.exports のオブジェクトである。exports に新しい値を代入しても、ローカル変数が変わるだけで、新しいオブジェクトはエクスポートされない。
押さえどころ
エクスポートする値を置き換えるには module.exports = ... を使う。exports.name = ... は、プロパティの追加にだけ使う。