Creating Custom Defined Objects

As you have seen so far, using the built-in JavaScript objects has several advantages. As you begin to write code that uses more and more data, you will find yourself wanting to build your own custom objects, with specific properties and methods.

You can define JavaScript objects in a couple of ways. The simplest is the on-the-fly method: Simply create a generic object and then add properties to it as needed. For example, to create a user object and assign a first and last name as well as define a function to return them, you could use the following code:

var user = new Object();
user.first="Brad";
user.last="Dayley";
user.getName = function( ) { return this.first + " " + this.last; }

You could also accomplish the same effect through a direct assignment using the following code, where the object is enclosed in {} and the properties are defined using property:value syntax:

var user = {
  first: 'Brad',
  last: 'Dayley',
  getName: function( ) { return this.first + " " + this.last; }};

These first two options work very well for simple objects that you do not need to reuse later. A better method for reusable objects is to actually enclose an object inside its own function block. This has the advantage of enabling you to keep all the code pertaining to the object local to the object itself. For example:

function User(first, last){
  this.first = first;
  this.last = last;
  this.getName = function( ) { return this.first + " " + this.last; };
var user = new User("Brad", "Dayley");

The end result of these methods is essentially the same as if you have an object with properties that can be referenced using dot notation, as shown here:

console.log(user.getName());

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset