Skip to main content

OOJS : Create an Object in Javascript

Points To Remember


  • You can create objects of a function in javascript.
  • Function can have both private and public methods.
  • Functions can inherit other functions

Create an Object in Javascript

Let us create a User object in javascript.

var User = function() {
_self = this;
var _name;
_self.getName = function() {
return _name;
}
_self.setName = function(name) {
_name = name;
}
_self.toString = function() {
return "Person{name::" + _name + "}";
}
}

Here User is a function

  • name is a private variable and will not be accessible outside the User function.
  • _self is used to save the this reference, this is done so that it does not mix with the this of the inner functions.
  • getName, setName and toString are the public functions that can be called from an object of User function.

typeof User
"function"

Now let us create two Objects of the User function.

var user1 = new User();
var user2 = new User();

Both user1 and user2 are the objects of the User function, and they are not equal to each other, i.e they are two different objects.

typeof user1
"object"

typeof user2
"object"

user1 == user2
false

user1 === user2
false

Now let us call the functions on the user objects.

user1.getName()
undefined

user1.setName("ekiras");
undefined

user1.getName();
"ekiras"

user1.toString();
"Person{name::ekiras}"

Comments