Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating javascript objects from different files

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...

like image 469
Danny Avatar asked Jan 15 '13 10:01

Danny


2 Answers

class methods should be defined via prototype so they receive 'this' reference, like that:

Person.prototype.getGender = function()
{
  return this.gender;
};
like image 156
VB9-UANIC Avatar answered Sep 29 '22 11:09

VB9-UANIC


Currently JavaScript is not clever enough to find your dependencies without help.

You need:

<!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>

Note:

If you want on-demand load of the dependencies then you can use AMD (Asynchronous Module Definition) with requirejs or something else.

Using AMD you can define something like:

define(['Job', 'person'], function (job, person) {
    //Define the module value by returning a value.
    return function () {};
});

The define method accepts two arguments: dependencies and function which defines the module. When all dependencies are loaded they are passed as arguments to the function where is the module definition.

One more thing to notice is that Person and Job are not classes. They are just functions (constructor functions) which produces objects based on rules in their definitions.


like image 28
Minko Gechev Avatar answered Sep 29 '22 12:09

Minko Gechev