Objects in Javascript

Declaring an object in Javascript can be done in various ways.

Object Literal Notation
This creates a single object. Initiating an object with literal notation goes like this:

var anne = {
   name: "Anne",
   age: 32
 // adding functions
  speak: function () {
 //   code;
 };
};

where the properties are given as a hash with key: value

Object Constructor

Initiating an object goes like this:

function Person(name,age){
  this.name = name;
  this.age = age;
// adding functions: 
  this.speak = function (){
  // code
 };
};

Instantiating a Person object then goes like this:

var laura = new Person ("Laura",89);
// the "laura" variable has access to all the methods within the object: 
laura.speak();

If you’re unfamiliar with the “this” keyword, all it does is refers to the object in question when creating an instance. So for example, using the code above:

laura.age

Would make “this” equal to the “laura” variable. So essentially this.age becomes varname.age.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>