4/22/2015

Javascript: How to create an Object

It's been a while since I've used Javascript extensively, so forgive me if I'm not entirely accurate on this. But, here some basics about Objects.

There are basically two ways to make objects.

METHOD #1 -- Create a blank Object 


Here, you can use the reserved JS object, called "Object" with a capital "O". And then use dot notation to add properties and methods.

creature = new Object();
creature.name = name;
creature.size = size;

creature.color = color;

METHOD #2 - Similar to an Array


Here, we assign attributes and methods to a variable, sort of like name-value pairs in an array.

To create an Object with instantiated values (called "creature"):


var creature = { 
  name:"elephant",  
  size: "big",
  color: "gray"
};

To retrieve a public value from the Object  (alert the name of the creature):


   window.alert (creature.name);

To include method / function in the Object (get a self description of the creature):


var creature = { 
  name:"elephant",  
  size: "big",
  color: "gray",
  description: function () {
    return "The " + this.name + " is " + this.size + " and " + this.color + ".";
  }
};

window.alert(creature.description()); 
// NOTE: "this." is added to the variable names to indicate that they are coming from within the object itself
// NOTE: Invoking requires parentheses to indicate it is a method, otherwise actual code might be returned instead

Any new variables that refer to creature, are by reference, meaning, that "dumbo" and "jumbo" and "creature" are all the same object in this example. 

var dumbo = creature; // refers to creature
var jumbo = creature; // refers to creature

So, any changes made to one, will make a change to all.

METHOD #3 -- Create Using a Prototype

In Method #2, the name of the original object was "creature". However, you can use an object as a "prototype" blueprint to create other objects, rather than it being used an object in the program actual object. To do this, use the "Object.create(prototypeName)" function.

jumbo = Object.create(creature); // separate copy of creature
dumbo = Object.create(creature); // separate copy of creature

In this example, "creature" is an object unto itself, and "jumbo" and "dumbo" are derivatives of the original "creature" object. Any changes made to the structure of "creature" will be reflected in jumbo and dumbo. However, changes made to property values of the original "creature" prototype will not be reflected in either "jumbo" or "dumbo."

METHOD #4 -- Constructor Function

Here, we use a constructor function. A special, reserved keyword, "this", is used by the object to refer back to itself.

function Creature (name, size,color) {
  this.name = name;
  this.size = size;
  this.color = color;
  this.description = function () {
    return "The " + this.name + " is " + this.size + " and " + this.color + ".";
  }
}
var creature = new Creature("elephant","big","gray");
console.log(creature.description());



Ways to Manipulate Objects

To copy an existing Object (called "vermin"):


vermin = Object.create (creature);

window.alert(vermin.description());
// NOTE: The values and methods of the "vermin" object are the exact same as the original "creature", so it is still describing an "elephant" at this point

To change values or methods of an Object:

You can use the dot method, or you can refer to the name of the property inside of square brackets:

vermin.name = "mouse";
vermin["name"] = "rat";
vermin.color = "brown";
vermin["size"] = "small";
vermin.favoriteFood = "cheese";
vermin.description = function() { return "I am the " + this.size + ", " + this.color + " " + this.name + ", and I like " + this.favoriteFood + "!" };

window.alert(vermin.description());
// NOTE: There are a couple of ways to change the values -- using dot-notation or using Array-styled references
// NOTE: The "name" variable is first changed to "mouse", then to "rat" -- so, the output will be "rat".


Passing an Object to a function passes as a reference


So, when you send an object to a function, and you change the values in the function, it will change the values of the Object outside of the function, too.

flower = {
  name: "rose", 
  color:"red", 
  description: function() {
    return "This " + this.name + " is " + this.color + ".";
  }
};
window.alert (flower.description());
// OUTPUT IS: "This rose is red."

function makeThingsYellow (objectSent) {
  objectSent.color = "yellow";
}

makeThingsYellow(flower);
window.alert (flower.description());
// OUTPUT IS: "This rose is yellow."


You can permanently "Freeze" an Object to protect its contents


Here, we'll try to change the flower to "pink" after choosing to freeze it, but you the output remains yellow. Important -- You cannot "unfreeze" an Object.

Object.freeze(flower);

function makeThingsPink (objectSent) {
  objectSent.color = "pink";
}

makeThingsPink(flower);
window.alert (flower.description()); 
// OUTPUT IS: "This rose is yellow."



No comments :

Post a Comment