MLNTN

Maniacal musings of a pixel perfectionist

Creating objects and methods

Posted by Jared on December 1, 2007

That’s right, object-oriented Javascript. Let’s get to it. We’re going to make an object for storing and retrieving user information.

Let’s start with the base object:

var User = function(firstName, lastName, emailAddress) {
}

We have to initialize the variables so that they’re available to the rest of the methods of this object:

var User = function(firstName, lastName, emailAddress) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.emailAddress = emailAddress;
}

Then let’s start creating the methods:

User.prototype = {
  add: function() {
    alert('User added: ' + this.getFullName());
  },
  changeEmail: function(email) {
    this.emailAddress = email;
    alert('E-mail address for '+ this.getFullName() +' changed to: ' + this.emailAddress);
  },
  getFullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
}

Lastly, let’s run the

add()

method when we setup a new user:

var User = function(firstName, lastName, emailAddress) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.emailAddress = emailAddress;
  this.add();
}

Alright, that’s all done. Now what do we do with this thing?

// alerts 'User added: Michael Bolton'
var michael = new User('Michael', 'Bolton', 'mbolton@initech.com');
// alerts 'E-mail address for Michael Bolton changed to: michael.bolton@initrode.com'
michael.changeEmail('michael.bolton@initrode.com');
// alerts 'Hello, Michael'
alert('Hello, ' + michael.firstName);

Here it is in one big snippet:

var User = function(firstName, lastName, emailAddress) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.emailAddress = emailAddress;
  this.add();
}

User.prototype = {
  add: function() {
    alert('User added: ' + this.getFullName());
  },
  changeEmail: function(email) {
    this.emailAddress = email;
    alert('E-mail address for '+ this.getFullName() +' changed to: ' + this.emailAddress);
  },
  getFullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
}

// alerts 'User added: Michael Bolton'
var michael = new User('Michael', 'Bolton', 'mbolton@initech.com');
// alerts 'E-mail address for Michael Bolton changed to: michael.bolton@initrode.com'
michael.changeEmail('michael.bolton@initrode.com');
// alerts 'Hello, Michael'
alert('Hello, ' + michael.firstName);

One Response to “Creating objects and methods”

  1. [...] how you could use it to extend the User object that we created earlier 1 2 3 4 5 6 7 8 9 addMethod(User.prototype, "find", function(){ // Find [...]

Leave a Reply