<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Javascript is just an Object

Published on
16,465 Points
3,365 Views
6 Endorsements
Last Modified:
Approved
Rob
I'm an enthusiastic Web Solutions Provider that designs and creates a website YOU want for you and your customers
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: http://e-e.com/Q_28383483.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.
6
Comment
Author:Rob
  • 5
  • 5
10 Comments

Expert Comment

by:K_dot
I copied your code in my editor to try it out.  But your code:
// public function	
	this.getDetails() {
		return all_details;
	}

Open in new window

is throwing an error:
Uncaught SyntaxError: uncaught token {

Open in new window

Could  you fix this please?  Thanks.
0
LVL 43

Author Comment

by:Rob
Thanks. I've looked at that long and tested it but must've changed this. Should be
// public function	
	this.getDetails = function() {
		return all_details;
	};

Open in new window

0

Expert Comment

by:K_dot
Thanks, Rob.  I tried that code before I posted, and though it didn't generate any errors, when I tried to log it out using this code:
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;
	}
}

var newPerson = person("Rob",30,"555-4255");
//newPerson.getDetails(); //returns the string "Rob 30 555-4255"
console.log(newPerson.getDetails());

Open in new window

I got this error Chrome 33.x Dev Tools console:
Uncaught TypeError:  Cannot call method 'getDetails' of undefined

Open in new window

What am I doing wrong?

Thanks!
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

LVL 43

Author Comment

by:Rob
I've tested it here ok http://jsbin.com/hovukeji/1/edit?js,console
What does it do for you
0

Expert Comment

by:K_dot
Thanks, Rob.  If you copy/paste my code in JSBIN, do you get the error I posted?  It appears the only difference in your code above and the code in the article is that you are replacing the variable "newPerson" with "p1".  That should make no difference.
http://jsbin.com/meqis/1/edit  I'm getting an error.  ??
0

Expert Comment

by:K_dot
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.
0
LVL 43

Author Comment

by:Rob
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.
0
LVL 43

Author Comment

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

Expert Comment

by:K_dot
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.
0
LVL 43

Author Comment

by:Rob
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
0

Featured Post

Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Join & Write a Comment

The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month