How can I split my javascript code into separate files?

前端 未结 3 1795
迷失自我
迷失自我 2021-01-30 18:11

I\'m reading the Javascript Guide from Mozilla And when they contrasted JS to Java , It got me thinking, Java code is easily split up with each class in his own file. after futh

3条回答
  •  轮回少年
    2021-01-30 18:42

    For small and medium projects like a website or game, the native namespacing and constructors work very well. They are a poor choice when the loading order is too complex to handle without some sort of autoloading.

    index.html:

    
    
    

    Manager.js:

    var Manager = function() {
        var employee1 = new window.Employee(this);
        var employee2 = new window.Employee(this);
    };
    

    Employee.js:

    var Employee = function(boss) {
        // work stuff here
        this.wage = 5;
    };
    

    Note, properties inside the employee constructor function are visible to the manager. The new word signals a constructor. This is also possible without a constructor by returning an object with properties instead of a function as shown above.

提交回复
热议问题