Alex Rivera | Logout

Why/How should I used objects in JavaScript?

Asked 2011-08-03T17:29:22.530
12

I understand how to instantiate objects and call them, but I just cannot find a reason to use them in my script. I could do

var obj = {
    hi: function() {
        return "Hello";
    }
}; 

but why can't I just do it the same way like:

function hi() {
    return "Hello";
}

I've never understood the reasons why I should use prototyping either. Most of the things I do in JavaScript I can do well without objects. But I want to use objects. What are objects for and what are the reasons why I should use them?

Edit
Report

2 Answers

17

Objects are useful for example for making a single unit out of values that belong together. Example:

function Person(firstName, lastName, gender, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.gender = gender;
  this.age = age;
}

Person.prototype = {
  getFullName: function() { return this.firstName + ' ' + this.lastName; },
  isMale: function() { return this.gender == 'Male'; },
  isFemale: function() { return this.gender == 'Female'; }
};

var amanda = new Person('Amanda', 'Smith', "Female", 42);
var john = new Person('John', 'Doe', 'Male', 72);

alert(amanda.getFullName());
alert(john.isMale());

Compared to the less structured:

function getFullName(firstName, lastName) {
  return firstName + ' ' + lastName;
}

function isMale(gender) {
  return gender == 'Male';
}

function isFemale(gender) {
  return gender == 'Female';
}

var amandaFirstName = 'Amanda';
var amandaLastName = 'Smith';
var amandaGender = 'Female';
var amandaAge = 42;
var johnFirstName = 'John';
var johnLastName = 'Doe';
var johnGender = 'Male';
var johnAge = 72;

alert(getFullName(amandaFirstName, amandaLastName));
alert(isMale(johnGender));
answered 2011-08-03T17:45:44.760
0

It tries to simulate the OOP paradigm that's all. There are various ways of doing this. But ask yourself, doe 'hi' belong in 'obj' or can it be a standalone function? Its all about how closely related is the function to the object. Does the function needs to access the objects private variables and such?

answered 2011-08-03T17:34:13.577

Your Answer