LoginSignup
18

More than 5 years have passed since last update.

RequireJSで循環参照

Posted at

ここを参考に、循環参照を解決する方法を記述する。

A.jsとB.jsがそれぞれのモジュールを相互に使いたい場合、以下のように、requireを使って、必要な時にモジュールを取得すれば良い。
そうしなければ、どちらかのモジュールは undefined になる。

A.js
define('A',['require', 'B'], function(require, B) {
    function A() {
        var B = require("B");
        this.name = "A";
        this.b = new B();
    }
    return A;
});
B.js
define('B',['require', 'A'], function(require, A) {
    function B() {
        var A = require("A");
        this.name = "B";
        this.a = new A();
    }
    return B;
});

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
18