02. Creating object

There are several ways we can create objects. The first is by scratch, where we can assign it variables and functions in an on-the-go type of manner. The second way of creating an object has to deal with classes, which define sets of objects that share the same properties and methods.

Creating object properties on-the-go

A very simple way to create objects is to declare it as a new Object, then start assigning it properties and methods.

var carInstance = {}; 
var carInstace = new Object();  // same empty object created as above
 
carInstance.color = "blue";
carInstance.make = "Toyota";
carInstance.model = Camry";
carInstance.velocity = 0;
carInstance.drive = function() { this.velocity = 100; } 

Now we have a carInstance object with various properties and one method. As you can tell, this wouldn't be the best way to create objects, as there is no set standard.

Deleting object properties

To delete an object properties, use the delete keyword.

delete carInstance.color; // true if successfully deleted 

Classes

Classes define sets of objects that share the same properties and methods. In our example, it'll be best to define a particular Car class, then instantiate each car instance from that class. This way, our code is cleaner and each object shares the same properties and methods as others of its type.

function Car(color, make, model, velocity) {
  this.color = color;
  this.make = make;
  this.model = model;
  this.velocity = velocity;
  this.drive = function(speed) {
    this.velocity = speed;
  }
} 

Now we can call a Carobject, pass in parameters, and have our object(s) created with ease. Furthermore, this makes it much easier especially when we have to create multiple objects.

var myCar = Car("red", "porsche", "911 turbo", "100");
var yourCar = Car("black", "BMW", "X5", "120");

Build modern and responsive webpages

High Performance Web Sites

Build modern and responsive webpages Try Front-end

Want your web site to display more quickly? This book presents 14 specific rules that will cut 25% to 50% off response time when users request a page. Author Steve Souders, in his job as Chief Performance Yahoo!, collected these best practices while optimizing some of the most-visited pages on the Web.

$ Check price
29.9929.99Amazon 4.5 logo(63+ reviews)

More Front-end resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad