Javascript is just an Object

RobOwner (Aidellio)
CERTIFIED EXPERT
I'm an enthusiastic IT Business Solutions Provider that designs and creates a solution YOU want for you and your customers
Published:
Updated:
This article is about getting you to think differently about Javascript's elements.  By element I'm referring to the primative types (boolean, number, string etc) but also arrays, dates, maths, regular expressions and functions.

I've been asked recently about scope, variables and anonymous functions, where it can get quite confusing understanding the relationships and the structure of the elements.  However, just thinking about them in a different way, and to me at least, it all started to make sense.

The purpose of this article is to reduce that confusion and simplify your understanding of the fundamentals of javascript.

All elements are Objects

Every element of javascript is a copy of the Object prototype but with it's own functions and properties.  You may or may not be familar with using objects in javascript but essentially you can capture any information in virtually any way.  An andress book entry object may look like this:
var myobject = { name: "Rob", address: "33 Over St", phone: 555-3745 };

Open in new window


Now you have an object that contains those name/value pairs.  The object can be passed to a function or sent over the internet so it's a great way to capture data in one place.
But what you've actually done is copy the generic Object prototype and added your own properties, ie name, address, phone.To reiterate, the generic Object protoype is a very simple object that every other element (including primative data types) is built on.  They are a copy of the prototype with their own functions and properties.

Object Oriented so where are the Classes

Javascript is object oriented but it's based on prototypes and not classes.  To simplify it, you can't create a class in Javascript but you can copy the simple Object prototype and emulate how classes work in other programming languages.

Functions are objects

When you create a function you're essentially copying the object prototype and creating a constructor.  A function is always assigned to a variable (anonymous functions we'll cover later), whether it's written like "var myfunction = function() {...}" or like "function myfunction() {...}" the result is the same.  The function is an object itself with basic properties that is copied to your myfunction variable, which in turn is attached to the global scope (We'll cover namespaces later as well to group your user defined objects together).

So what does this mean?  It means, that if you start to think of functions as object (and all types as objects) then understanding why Javascript does some unexpected things will make more sense.

Take the example from this question: https://www.experts-exchange.com/questions/28383483/Variable-passing-in-anonymous-functions.html.  The author asked why one scenario worked and another didn't.  The answer was simple if you thought of the function as an object and not a function (see the question for the details). It was also complicated by the use of anonymous funtions, which are functions not assigned to a variable. (See Anonymous functions below).

The example below shows how to create your very own "person" object.  There are private and public properties and functions that emulate how classes would be used in other languages.
function person(name, age, phone) {
                      	// some public variables	
                      	this.name = name;
                      	this.age = age;
                      	this.phone = phone;
                      	
                      	// a private! variable
                      	var all_details = name + " " + age + " " + phone;
                      	
                      	// public function	
                      	this.getDetails = function() {
                      		return all_details;
                      	};
                      }

Open in new window


You can now use this to create new objects with these properties and functions.
var newPerson = new person("Rob",30,"555-4255");
                      newPerson.getDetails(); //returns the string "Rob 30 555-4255"

Open in new window

Back to basics

Think of an array, eg [1,2,3,4,5,6,7].  
Assign this to a variable,
e.g.
var myarray = [1,2,3,4,5,6,7];

Open in new window

What you've done is essentially called the Array object's constructor with your values.  The Array prototype has attached functions and properties (just like the example above) to a copy of the Object prototype.  Then you have created a copy (loosely an instance) of the Array prototype and passed your values to the constructor to do wha tit needs to do to make it act like an array.  These functions and properties are what makes it an array.  The length property is one property that is used very frequently along with functions such as push(), pop() and sort().  In otherwords the Array primative type is still an object with functions and properties attached to a copy of the Object prototype.  Like I said before, everything is an Object.

Namespaces

A namespace is simply an Object that encapsulates all your variables and functions.  jQuery uses this to prevent conflicts with it's public properties and functions.  Otherwise there's the possibility of another library/framework (or even yourself) overwritting it without knowing. The reciprocal is true as well in that jQuery may overwrite one of your functions. It becomes extremely hard to debug so you're better off putting all your custom functions and variables into a namespace

Anonymous functions

This is just a function that is created, run and destroyed.  There are times when naming a function doesn't make sense or code just needs to execute once and finish.  Look into a javascript framework and see how this is more or less how the framework's namespace is set up.

The anonymous function is contained within brackets.  The additional brackets at the end of the code is what executes the function.  Without them the function is create then destroyed.
e.g.
(function() {
                      	alert("hi");
                      })();

Open in new window

This function can still be retained within an array with no variable name.
e.g.
// created
                      var myarray = [(function() {...})];
                      //then executed as many times as you wish
                      myarray[0]();

Open in new window

Extending the functionality of objects

You now understand that every element in Javascript is an object.
You also now know objects are very flexible in that they can be copied and modified easily to suit your intention. Then it may or may not have occured to you that you can modify the objects already available!

This makes extending the functionality of any object easy.  This doesn't just go for the primative types but also gives you the ability to build on other user defined objects, leading towards frameworks such as jQuery.

Using the prototype property of an object you are able to modify the functionality of an objects functions.
e.g.
// convert every element in an array to upper case
Array.prototype.myUcase=function()
                      {
                        for (i=0;i<this.length;i++)
                          {
                          this[i]=this[i].toUpperCase();
                          }
                      }
                      var fruits=["Banana","Orange","Apple","Mango"];
                      fruits.myUcase();

Open in new window

This outputs:
BANANA, ORANGE, APPLE, MANGO
Referenced: http://www.w3schools.com/jsref/jsref_prototype_array.asp

Conclusion

We've covered how functions and arrays are objects.  I've also shown how you can create your own "types" or user defined objects.

The same examples could be done for all the primative (and other) javascript types but the principle here is how they're ALL a copy of the Object prototype.
7
4,306 Views
RobOwner (Aidellio)
CERTIFIED EXPERT
I'm an enthusiastic IT Business Solutions Provider that designs and creates a solution YOU want for you and your customers

Comments (10)

Commented:
Ah, I see, in your code in the article above:
function person(name, age, phone) {
	// some public variables	
	this.name = name;
	this.age = age;
	this.phone = phone;
	
	// a private! variable
	var all_details = name + " " + age + " " + phone;
	
	// public function	
	this.getDetails = function() {
		return all_details;
	}
}

Open in new window

The semicolon is missing on line 13 where you define the getDetails function.  I see you have it in your JSBIN example, but not the code.  I don't have it in my JSBIN example either and that may be what is throwing the error.
RobOwner (Aidellio)
CERTIFIED EXPERT
Most Valuable Expert 2015

Author

Commented:
Here's your code working: http://jsbin.com/lonevosa/1/edit

two things

1) There was a missing semicolon after the close curly bracket of the this.getDetails = function() { .... } ; (You should also see a warning message at the bottom of the javascript edit box that indicates this

2) The second and probably more fundamental, is you need to use the new operator to create an instance of the "person" object.  Otherwise you're just calling a function that doesn't return anything.
RobOwner (Aidellio)
CERTIFIED EXPERT
Most Valuable Expert 2015

Author

Commented:
The semicolon is not required but yes it should be there for conformity.  The main issue was the missing "new" operator

Commented:
Rob,

I copied and pasted your code as in your example.  It contained errors and I was letting you know about them.  In your example,
"You can now use this to create new objects with these properties and functions."
Here is your code:
var newPerson = person("Rob",30,"555-4255");
newPerson.getDetails(); //returns the string "Rob 30 555-4255"

Open in new window

You are not using the 'new' operator.  I am trying to learn from your examples.
RobOwner (Aidellio)
CERTIFIED EXPERT
Most Valuable Expert 2015

Author

Commented:
K_dot,

My sincere apologies.  You most certainly should be able to learn from the examples given and something has obviously gone amiss when I've pasted it here after completeing my obviously inadequate testing.

I appreciate your input and feedback and again thank you for picking this up.

I've submitted for review.

Cheers,

Rob

View More

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.