JAVASCRIPT: Creating objects and methods
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:
1 2 | 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:
1 2 3 4 5 | var User = function(firstName, lastName, emailAddress) { this.firstName = firstName; this.lastName = lastName; this.emailAddress = emailAddress; } |
Then let’s start creating the methods:
1 2 3 4 5 6 7 8 9 10 11 12 | 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:
1 2 3 4 5 6 | 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?
1 2 3 4 5 6 | // 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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); |
[...] 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 [...]