Creating javascript objects from different files

2019-04-06 02:33发布

I've been trying to do javascript for sometime now, but i want it to be "object-orientated" so I'm trying to create different javascript classes in different files and try to create an object and call it's methods in a different file function, but it doesn't seem to work.

This is what I have so far:

person.js

function Person(name, age, gender)
{
    this.age = age;
    this.name = name;
    this.gender = gender;

    this.job;

    this.setJob = function(job)
    {
        this.job = job;
    }

    this.getAge = function()
    {
        return this.age;
    }

    this.getName = function()
    {
        return this.name;
    }

    this.getGender = function()
    {
        return this.gender;
    }
}

Job.js

function Job(title)
{
    this.title = title;
    this.description;

    this.setDescription = function(description)
    {
        this.description = description;
    }
}

main.js

function  main()
{
    var employee = new Person("Richard", 23, male);
    document.getElementById("mainBody").innerHTML = employee.getName();
}

index.html

<!DOCTYPE HTML>
<HTML>
<head>
    <title>javascript test</title>
    <script src="main.js" type="javascript"></script>
</head>
<body>
    <p id="mainBody"></p>
</body>
</HTML>

any help or advice would be greatly appreciated.

Many thanks

EDIT: Many thanks for all the answers and suggestions, however, I've included all my javascript files and still it doesn't work...

9条回答
家丑人穷心不美
2楼-- · 2019-04-06 03:22

you can try to include the 1st and 2nd javascript files first. like:

<!DOCTYPE HTML>
<HTML>
<head>
    <title>javascript test</title>
    <script src="person.js" type="javascript"></script>
    <script src="Job.js" type="javascript"></script>
    <script src="main.js" type="javascript"></script>
</head>
<body>
    <p id="mainBody"></p>
</body>
</HTML>
查看更多
做个烂人
3楼-- · 2019-04-06 03:25

This isn't working because, according to your HTML code, the browser is only loading main.js

<script src="main.js" type="javascript"></script>

Since Javascript runs in the browser, not on the server where the other files are, the browser will try to execute main.js and fail, since it doesn't have access to the classes in the other files. If you include each one of the files (making sure that every file is included after the one it requires), you should have more success.

For example:

<script src="Job.js" type="javascript"></script>
<script src="person.js" type="javascript"></script>
<script src="main.js" type="javascript"></script>
查看更多
仙女界的扛把子
4楼-- · 2019-04-06 03:34

ES6: https://www.sitepoint.com/understanding-es6-modules/

Supported in Safari as of Summer of 2017, but no support in other browsers. In a year or so, it seems like it'll be supported by Edge, Firefox, Chrome, Opera, and safari. So keep it in mind?

https://caniuse.com/#feat=es6-module

查看更多
登录 后发表回答