Skip to main content

JavaScript Object-Oriented Programming Part 1

By Ryan Frishberg



😳 Ever felt a little embarassed sharing your JavaScript? Let's fix it.

Object Categories

There are three object categories in JavaScript: Native Objects, Host Objects, and User-Defined Objects.

Native objects are those objects supplied by JavaScript. Examples of these are String, Number, Array, Image, Date, Math, etc.

Host objects are objects that are supplied to JavaScript by the browser environment. Examples of these are window, document, forms, etc.

And, user-defined objects are those that are defined by you, the programmer.

A fundamental concept in JavaScript is that every element that can hold properties and methods is an object, except for the primitive data types. We can use JavaScript’s built-in constructor functions (just like the ones we’ve created) to create objects:

var Image1 = new Image(50,100);    
Image1.src = "myDog.gif";

Here we’ve created a new Image object using the native Image() constructor function with the following properties:

  • width = 50
  • height = 100
  • src = "myDog.gif"

JavaScript also includes an Object() constructor function that can be used to define a new Object object:

var myObj = new Object();

To that "base Object", we can add properties/methods. Every object in JavaScript derives from JavaScript’s native Object object.

Let’s review a String primitive data type:

var myString = "This is my string";    
alert(myString); // displays "This is my string"    
alert(typeof myString); // displays "string"

However, we can even make a String an object, by using its constructor function:

var myString = new String("This is my string");    
alert(myString); // displays "This is my string"    
alert(typeof myString); // displays "object"

Now we’ve created a String object. We can also do the same with Number and Boolean. But why would we want to? Well, once we’ve done that, we can add distinctive properties and methods to that object. A primitive data type contains the properties and methods laid out in its object constructor, but it cannot, itself, hold any distinctive properties/methods. For example, a String primitive data type contains the length property as well as the many methods defined in the native String() object constructor, such as substring(). However, a String object contains the properties and methods defined in the String() object constructor as well as any unique values assigned to that particular object. Now, let’s create a Number object and add a method to it:

var myNumber = new Number(2);    
myNumber.doubleIt = new Function("return this*2");    
alert(myNumber.doubleIt()); // displays 4    
alert(typeof myNumber); // displays "object"

So, we just created a new Number object, and then we defined a method for it, doubleIt(). Note that typeof myNumber is "object". This is because objects are able to contain unique properties and methods. Primitive data types, such as String, Boolean, Number, Undefined, and Null, cannot, and this is what differentiates the two.

Also, in the example above, we’ve in fact created another object – a Function object. However, the Function object is different. When we create an object, we first enter the new keyword, then follow it with the object constructor function, and this returns a new instance of that particular object. Then, using the returned value (which we usually assign to a variable), we can add properties and methods to that object. However, because a Function object is also a callable block of code, JavaScript makes the distinction and tells us that it’s not only an object (which it is, as we can add properties and methods to it), but is also a callable block of code. So, when we enter:

alert(typeof myNumber.doubleIt) // displays "function"

it displays "function", rather than "object" as you might have expected. The Function() constructor function can take more arguments. The last argument passed to the Function() constructor becomes the body of the function, while the others become parameters:

var myFunc = new Function("parameter1","parameter2",    
 "parameter3"," // function body");

Now we can call that function and specify three arguments:

Function Objects

JavaScript’s Function object is unususal for a number of reasons. Firstly, it’s a callable block of code. And a function is always an object – it always has the ability to hold unique properties and methods. The creation of a function automatically creates a Function object:

function myFuncObj(){}    
myFuncObj.someVariable = "x";    
alert(myFuncObj.someVariable) // displays "x"    

Even without the new keyword, Function() creates an object, capable of containing properties and methods. Note that the Function() constructor is a special case – all other constructors must be called with the new keyword, or they simply return a value, instead of a new object.

Let’s look at a String primitive data type vs. a String object:

var pimitiveString1 = "This is a primitive string";    
var pimitiveString2 = String("This is a primitive string");    
var stringObject = new String("This is a String object");    
primitiveString1.prop = "This is a property";    
primitiveString2.prop = "This is a property";    
stringObject.prop = "This is a property";    
alert(primitiveString1.prop) // displays "undefined"    
alert(primitiveString2.prop) // displays "undefined"    
alert(stringObject.prop) // displays "This is a property"    
alert(typeof primitiveString1); // displays "string"    
alert(typeof primitiveString2); // displays "string"    
alert(typeof stringObject) // displays "object"

Here you can see that, without the new keyword, we don’t create and assign an object to a variable, but instead, we assign the returned value (which is a primitive data type, String) to a variable. You can also see that primitiveString1 and primitiveString2 are not objects, as we cannot assign them properties. Note that primitiveString1/primitiveString2 and stringObject return different results when used with the typeof operator. This is even true for Date, Image, Option, and other objects. For example:
var x = Date();    
alert(typeof x); // displays "string"

No matter how you create a function (there are numerous ways), you’ll automatically create an object:

var myFuncObj = new Function();    
var myFuncObj = Function();    
var myFuncObj = function(){}    
function myFuncObj(){}

Here, we’ve examined the different ways to create a Function object that’s capable of holding a callable block of code, as well as any disctinct properties or methods.

In Summary

Before we move on, let’s review some key points:

  • In JavaScript, there are five primitive data types: Undefined, Null, Boolean, Number, and String.
  • In JavaScript, everything is an object, except for the primitive data types.
  • An object is an unordered collection of properties. Properties may represent primitive data types, objects, or Function objects, in which case they are called "methods".
  • There are three main object categories in JavaScript: native objects, host objects, and user-defined objects.
  • There are many built-in, native objects, such as Object, Image, Date, Option, etc. However, we can also create our own user-defined objects, such as the Circle object.
  • An object constructor/object constructor function is a function that’s used to define a new object. In this function, we declare the initial properties/methods of the new object, and usually assign them a pre-defined value.
  • To create an instance of an object, we use the keyword "new", followed by an object constructor. We can either use JavaScript’s built-in constructors to create a native object, or we can build our own constructors to create a user-defined object.
  • Every object method has a variable – this – which refers to the current instance of that object from which the method is called. Example:
    • myObj.myFunc()
    • yourObj.myFunc()

    In the first example, in myFunc(), the variable this would refer to myObj. However, in the second example, in myFunc(), the variable this would refer to yourObj.

Look out for Part 2, where we’ll explore Arguments, the Prototype Property, and Constructors, next week on SitePoint…

If you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like JavaScript Programming for the Web.

Go to page: 1 | 2 | 3 | 4

Ryan has been involved with client-side scripting since 1999 when he started high school. He was part of the Flex SDK team and is now a software consultant.

New books out now!

💁‍♀️ Fun Fact: Python was ranked #2 on a recent highest paid coders list. *

🤓 Ok. When did a code editor from Microsoft become kinda cool!?