-2

I just started working on Javascript project. I know a couple of things

I have one js file called Employee and it has following methods:

  1. AddEmployee
  2. Search Employee
  3. Third Employee

In Java, you access all the methods using object like employeeObj.addEmployee(); I want to achieve same thing in JavaScript. Meaning, I want to access all the methods by creating an employee object?

user1030128
  • 411
  • 9
  • 23
  • can you show us what you have so far? Generally if you want a good answer on this site it helps to show that you've put some effort in and to ask a specific question – Ben McCormick Jun 13 '13 at 15:17
  • I would suggest doing this small course http://www.codecademy.com/tracks/javascript You probably need chapter 7 and 8 but taking the whole course shouldn't take long and is the suggested way to go. – MrSoundless Jun 13 '13 at 15:19
  • It is very hard for us to infer what your code looks like and suggest the correct strategy. Would you mind including some (sample, reduced case) code for that external file? – Benjamin Gruenbaum Jun 13 '13 at 15:20
  • possible duplicate of [How to "properly" create a custom object in JavaScript?](http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript) – Ben McCormick Jun 13 '13 at 15:25

2 Answers2

1

One of the way you can achieve OOP in Javascript

function Foo()
{
    this.x = 1;
}

Foo.prototype.AddX = function(y)    // Define Method
{
    this.x += y;
}

obj = new Foo;

obj.AddX(5);                        // Call Method

you can refer to few online tutorials for that

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
  2. http://mckoss.com/jscript/object.htm
  3. http://www.javascriptkit.com/javatutors/oopjs.shtml
HaBo
  • 13,999
  • 36
  • 114
  • 206
  • Really? _THAT_ is how you do OOP in JavaScript? There are a million ways to do OOP in JavaScript, you have not suggested how you'd solve OP's issue. This is basically just a link to a bunch of tutorials. – Benjamin Gruenbaum Jun 13 '13 at 15:23
  • @BenjaminGruenbaum Obviously, I suggested One of the way to achieve OO. May be I should rewrite my line. Thanks :) – HaBo Jun 13 '13 at 15:51
0

There are a few ways to create objects in javascript. If you just want a container for your functions the easiest way is to create a simple object with the functions as properties.

var employeeObj = {

  addEmployee: function(){
  },
  searchEmployee: function(){
  },
  thirdEmployee: function() {
  }
};

If you need the object to be able to reference itself during initial set up, you can use a constructor function

var Employee = function() {

}

Employee.prototype.addEmployee = function(){};
Employee.prototype.searchEmployee = function(){};
Employee.prototype.thirdEmployee = function(){};

var employeeObj = new Employee();
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71