The Basics of Object-Oriented JavaScript

The Basics of Object-Oriented JavaScript

Over recent years, JavaScript has increasingly gained popularity, partly due to libraries that are developed to make JavaScript apps/effects easier to create for those who may not have fully grasped the core language yet.

While in the past it was a common argument that JavaScript was a basic language and was very ‘slap dash’ with no real foundation; this is no longer the case, especially with the introduction of high scale web applications and ‘adaptations’ such as JSON (JavaScript Object Notation).

JavaScript can have all that an Object-Orientated language has to offer, albeit with some extra effort outside of the scope of this article.

Let’s Create an Object

    function myObject(){
    
    };

Congratulations, you just created an object. There are two ways to
create a JavaScript object: they are ‘Constructor functions’ and
‘Literal notation’. The one above is a Constructor function,
I’ll explain what the difference is shortly, but before I do, here
is what an Object definition looks like using literal notation.

    var myObject = {
    
    };

Literal is a preferred option for name spacing so that your JavaScript
code doesn’t interfere (or vice versa) with other scripts running on the
page and also if you are using this object as a single object and not requiring
more than one instance of the object, whereas Constructor function type
notation is preferred if you need to do some initial work before the object
is created or require multiple instances of the object where each instance
can be changed during the lifetime of the script. Let’s continue to build
on both our objects simultaneously so we can observe what the differences are.

Defining Methods and Properties

Constructor version:

    function myObject(){
        this.iAm = 'an object';
        this.whatAmI = function(){
            alert('I am ' + this.iAm);
        };
    };

Literal version:

    var myObject = {
        iAm : 'an object',
        whatAmI : function(){
            alert('I am ' + this.iAm);
        }
    }

For each of the objects we have created a property ‘iAm’ which contains a
string value that is used in our objects method ‘whatAmI’ which alerts a message.

Properties are variables created inside an object and methods are functions created inside an object.

Now is probably as good a time as any to explain how to use properties and
methods (although you would already have done so if you are familiar with a library).

To use a property first you type what object it belongs to – so in this case it’s myObject –
and then to reference its internal properties, you put a full stop and then the name of the
property so it will eventually look like myObject.iAm (this will return ‘an object’).

For methods, it is the same except to execute the method, as with any function, you must
put parenthesis after it; otherwise you will just be returning a reference to the function
and not what the function actually returns. So it will look like myObject.whatAmI()
(this will alert ‘I am an object’).

Now for the differences:

  • The constructor object has its properties and methods defined with the
    keyword ‘this’ in front of it, whereas the literal version does not.
  • In the constructor object the properties/methods have their ‘values’
    defined after an equal sign ‘=’ whereas in the literal version, they are
    defined after a colon ‘:’.
  • The constructor function can have (optional) semi-colons ‘;’ at the
    end of each property/method declaration whereas in the literal version
    if you have more than one property or method, they MUST be separated with
    a comma ‘,’, and they CANNOT have semi-colons after them, otherwise JavaScript will return an error.

There is also a difference between the way these two types of object declarations are used.

To use a literally notated object, you simply use it by referencing its variable name,
so wherever it is required you call it by typing;

    myObject.whatAmI();

With constructor functions you need to instantiate (create a new instance of)
the object first; you do this by typing;

    var myNewObject = new myObject();
    myNewObject.whatAmI();

Using a Constructor Function.

Let’s use our previous constructor function and build upon it so it performs some basic
(but dynamic) operations when we instantiate it.

    function myObject(){
        this.iAm = 'an object';
        this.whatAmI = function(){
            alert('I am ' + this.iAm);
        };
    };

Just like any JavaScript function, we can use arguments with our constructor function;

function myObject(what){
	this.iAm = what;
	this.whatAmI = function(language){
		alert('I am ' + this.iAm + ' of the ' + language + ' language');
	};
};

Now let’s instantiate our object and call its whatAmI method, filling in the required
fields as we do so.

    var myNewObject = new myObject('an object');
    myNewObject.whatAmI('JavaScript');

This will alert ‘I am an object of the JavaScript language.’

To Instantiate or not to Instantiate

I mentioned earlier about the differences between Object Constructors and Object Literals and that
when a change is made to an Object Literal it affects that object across the entire script, whereas when
a Constructor function is instantiated and then a change is made to that instance, it won’t affect any
other instances of that object. Let’s try an example;

First we will create an Object literal;

	var myObjectLiteral = {
    	myProperty : 'this is a property'
    }
    
    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'
    
    //change myProperty
    myObjectLiteral.myProperty = 'this is a new property';
    
    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a new property', as expected

Even if you create a new variable and point it towards the object, it will have the same effect.

	var myObjectLiteral = {
    	myProperty : 'this is a property'
    }
    
    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'
    
    //define new variable with object as value
    var sameObject = myObjectLiteral;
    
    //change myProperty
    myObjectLiteral.myProperty = 'this is a new property';
    
    //alert current myProperty
    alert(sameObject.myProperty); //this will still alert 'this is a new property'

Now let’s try a similar exercise with a Constructor function.

	//this is one other way of creating a Constructor function
	var myObjectConstructor = function(){
    	this.myProperty = 'this is a property'
    }
    
    //instantiate our Constructor
    var constructorOne = new myObjectConstructor();
    
    //instantiate a second instance of our Constructor
    var constructorTwo = new myObjectConstructor();
    
    //alert current myProperty of constructorOne instance
    alert(constructorOne.myProperty); //this will alert 'this is a property'
     
     //alert current myProperty of constructorTwo instance
    alert(constructorTwo.myProperty); //this will alert 'this is a property'    

So as expected, both return the correct value, but let’s change the myProperty for one of the instances.

	//this is one other way of creating a Constructor function
	var myObjectConstructor = function(){
    	this.myProperty = 'this is a property'
    }
    
    //instantiate our Constructor
    var constructorOne = new myObjectConstructor();
    
    //change myProperty of the first instance
    constructorOne.myProperty = 'this is a new property';
    
    //instantiate a second instance of our Constructor
    var constructorTwo = new myObjectConstructor();
    
    //alert current myProperty of constructorOne instance
    alert(constructorOne.myProperty); //this will alert 'this is a new property'
     
     //alert current myProperty of constructorTwo instance
    alert(constructorTwo.myProperty); //this will still alert 'this is a property'    

As you can see from this example, even though we changed the property of constructorOne
it didn’t affect myObjectConstructor and therefore didn’t affect constructorTwo. Even if
constructorTwo was instantiated before we changed the myProperty property of constructorOne,
it would still not affect the myProperty property of constructorTwo as it is a completely different
instance of the object within JavaScript’s memory.

So which one should you use? Well it depends on the situation, if you only need one object of its kind for
your script (as you will see in our example at the end of this article), then use an object literal, but if you need several instances of an object, where each instance
is independent of the other and can have different properties or methods depending on the way it’s constructed, then use a constructor function.

This and That

While explaining constructor functions, there were a lot of ‘this’ keywords being thrown around
and I figure what better time to talk about scope!

Now you might be asking ‘what is this scope you speak of’?’ Scope in JavaScript is function/object based, so that means if you’re outside
of a function, you can’t use a variable that is defined inside a function (unless you use a closure).

There is however a scope chain, which means that a function inside another function can access a
variable defined in its parent function. Let’s take a look at some example code.

<script type="text/javascript">

var var1 = 'this is global and is available to everyone';

function function1(){

	var var2 = 'this is only available inside function1 and function2';	
	
	function function2(){
	
		var var3 = 'this is only available inside function2';
	
	}		
	
}

</script>

As you can see in this example, var1 is defined in the global object
and is available to all functions and object, var2 is defined inside function1
and is available to function1 and function2, but if you try to reference it from the global object
it will give you the error ‘var2 is undefined’, var3 is only accessible to function2.

So what does ‘this’ reference? Well in a browser, ‘this’ references the window object, so technically
the window is our global object. If we’re inside an object, ‘this’ will refer to the object itself however
if you’re inside a function, this will still refer to the window object and likewise if you’re inside a method
that is within an object, ‘this’ will refer to the object.

Due to our scope chain, if we’re inside a sub-object (an object inside an object), ‘this’ will refer to
the sub-object and not the parent object.

As a side note, it’s also worth adding that when using functions like setInterval, setTimeout and eval,
when you execute a function or method via one of these, ‘this’ refers to the window object as these are methods of window, so
setInterval() and window.setInterval() are the same.

Ok now that we have that out of the way, let’s do a real world example and create a
form validation object!

Real world Usage: A Form Validation Object

First I must introduce you to the addEvent function which we will create and is a
combination of ECMAScript’s (Firefox, Safari, etc.. ) addEventListener() function and
Microsoft ActiveX Script’s attachEvent() function.

    function addEvent(to, type, fn){
        if(document.addEventListener){
            to.addEventListener(type, fn, false);
        } else if(document.attachEvent){
            to.attachEvent('on'+type, fn);
        } else {
            to['on'+type] = fn;
        }	
    };

This creates a new function with three arguments, to being the DOM object we are attaching
the event to, type being the type of event and fn being the function run when
the event is triggered. It first checks whether addEventListener is supported, if so it will use that, if not it will check
for attachEvent and if all else fails you are probably using IE5 or something equally obsolete so
we will add the event directly onto its event property (note: the third option will overwrite any
existing function that may have been attached to the event property while the first two will add
it as an additional function to its event property).

Now let’s set up our document so it is similar to what you might see when you develop jQuery stuff.

In jQuery you would have;

    $(document).ready(function(){
        //all our code that runs after the page is ready goes here
    });

Using our addEvent function we have;

    addEvent(window, 'load', function(){
		//all our code that runs after the page is ready goes here
	});

Now for our Form object.

var Form = {

	validClass : 'valid',
	
	fname : {
		minLength : 1,		
		maxLength : 15,	
		fieldName : 'First Name'
	},
    
	lname : {
		minLength : 1,		
		maxLength : 25,
		fieldName : 'Last Name'
	},
	
    
	validateLength : function(formEl, type){
		if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){	
			formEl.className = formEl.className.replace(' '+Form.validClass, '');
			return false;
		} else {
			if(formEl.className.indexOf(' '+Form.validClass) == -1)
			formEl.className += ' '+Form.validClass;
			return true;
		}
	},
	
    
	validateEmail : function(formEl){
		var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
		var emailTest = regEx.test(formEl.value);		 
		if (emailTest) {
			if(formEl.className.indexOf(' '+Form.validClass) == -1)			
			formEl.className += ' '+Form.validClass;            
			return true;
		} else {
			formEl.className = formEl.className.replace(' '+Form.validClass, '');
			return false;
		}			
	},		
	
	getSubmit : function(formID){    
		var inputs = document.getElementById(formID).getElementsByTagName('input');
		for(var i = 0; i < inputs.length; i++){
			if(inputs[i].type == 'submit'){
				return inputs[i];
			}		
		}		
		return false;
	}			
		
};

So this is quite basic but can easily be expanded upon.

To break this down first we create a new property which is just the string name of our 'valid' css class
that when applied to the form field, adds valid effects such as a green border. We also define our two sub-objects, fname and lname,
so we can define their own properties that can be used by methods elsewhere, these properties are minLength
which is the minimum amount of characters these fields can have, maxLength which is the max characters
the field can have and fieldName which doesn't actually get used, but could be grabbed for
things like identifying the field with a user friendly string in an error message (eg. 'First Name field is required.').

Next we create a validateLength method that accepts two arguments: formEl the DOM element to validate
and the type which refers to one of the sub-object to use (i.e. fname or lname).
This function checks whether the length of the field is between the minLength and maxLength range, if it's not
then we remove our valid class (if it exists) from the element and return false, otherwise if it is then we add the valid class and return true.

Then we have a validateEmail method which accepts a DOM element as an arguement, we then test this DOM elements value against an
email type regular expression; again if it passes we add our class and return true and vice versa.

Finally we have a getSubmit method. This method is given the id of the form and then loops through all input elements inside the specified form
to find which one has a type of submit (type="submit"). The reason for this method is to return the submit button so we can
disable it until the form is ready to submit.

Let's put this validator object to work on a real form. First we need our HTML.

    <body>
    
    <form id="ourForm">
        <label>First Name</label><input type="text" /><br />
        <label>Last Name</label><input type="text" /><br />
        <label>Email</label><input type="text" /><br />
        <input type="submit" value="submit" />
    </form>
    
    </body>

Now let's access these input objects using JavaScript and validate them when the form submits.

addEvent(window, 'load', function(){
	
	
	var ourForm = document.getElementById('ourForm');	
	var submit_button = Form.getSubmit('ourForm');
	submit_button.disabled = 'disabled';
	
	function checkForm(){
		var inputs = ourForm.getElementsByTagName('input');
		if(Form.validateLength(inputs[0], Form.fname)){
			if(Form.validateLength(inputs[1], Form.lname)){
				if(Form.validateEmail(inputs[2])){ 					 
                     
						submit_button.disabled = false;
						return true;
										
				}
			}
		}
			
		submit_button.disabled = 'disabled';
		return false;
		
	};
	
	checkForm();		
	addEvent(ourForm, 'keyup', checkForm);
	addEvent(ourForm, 'submit', checkForm);
      
	
});

Let's break down this code.

We wrap our code in the addEvent function so when the window is loaded this script runs.
Firstly we grab our form using its ID and put it in a variable named ourForm, then we grab
our submit button (using our Form objects getSubmit method) and put it in a variable named submit_button,
and then set the submit buttons disabled attribute to 'disabled'.

Next we define a checkForm function. This stores all the inputs inside the form field as an array and we attach it to a
variable named.. you guessed it.. inputs!
Then it defines some nested if statements which test each of the fields inside the inputs array against our Form methods.
This is the reason we returned true or false in our methods, so if it returns true, we pass that if statement and continue onto the next,
but if it returns false, we exit the if statements.

Following our function definition, we execute the checkForm function when the page initially loads and also attach the function to a keyup event
and a submit event.

You might be asking, why attach to submit if we disabled the submit button. Well if you are focused on an input field and hit the enter key, it will
attempt to submit the form and we need to test for this, hence the reason our checkForm function returns true (submits the form) or false (doesn't submit form).

Conclusion

So we learned how to define the different object types within JavaScript and create properties and methods within them. We also learned a nifty addEvent function and got to use our object in a basic real world example.

This concludes the basics of JavaScript Object Orientation. Hopefully, this may start you on your way to building your own JavaScript library! If you liked this article and are interested in other JavaScript related topics, post them in the comments as I'd be happy to continue writing them. Thanks for reading.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Robert

    Really great to see something else than just jQuery love, people seem to forget how powerful JavaScript itself is, even though it’s a very complex language once you get a hold of it. I’m still learning C++ though as a foundation for JavaScript, even though I can program in JS.

    • Robert

      I also forgot to add to people using jQuery, a tip of mine is to learn JavaScript before you learn jQuery. It will be alot easier for you to understand what jQuery does under “the hood”… And you will get a better understanding of JavaScript

      • http://www.wdonline.com Jeremy

        100% agree. What people seem to forget is jQuery, and any other JavaScript framework, is still based on JavaScript. Any code you write using a framework is still bound to the rules of JavaScript. Thus a knowledge of the fundamentals is key to writing effective code.

  • Pete

    What’s the diff between:

    function Car() {}
    and
    var Car = function(){}

    Why one over the other? Any reason to choose either style?

    • http://www.wdonline.com Jeremy McPeak

      The first is function declaration and the second is a function expression.

      Declaring a function is advantageous in that the interpreter loads the function before any code executes. Functions that are assigned to a variable (function expressions) are not loaded until code execution reaches that line. Other than that, there’s not really any other difference.

      Personally, I declare all functions/constructors, and I define methods on the constructor function’s prototype using function expressions.

      • neoprabhu

        Thanx jermy, that is useful to me …

  • Alex

    Can’t you use an objects prototype method to add/change properties to all existing/new created instances of it regardless of which notation you used?

  • SwedishChef

    Isn’t function myObject(){ a Function object?

    • Leigh Kaszick
      Author

      Any function is technically an object, but in the case of myObject, it became a constructor function as soon as we referenced ‘this’ inside it (dynamic power of JS right there), which means it has to be instantiated with the new operator.

  • http://blog.jeremymartin.name Jeremy Martin

    Firstly, I appreciate the article since it’s clear you spent some real time on it. But it must be said that this is very misleading and confuses a lot of “the basics” of OO in JavaScript. JavaScript DOES contain a terminological collision between javascript *object* notation (json) and *objects* that are instantiated from a class definition – but they are not nearly so related as this article suggests. Suggested reading: https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript and http://json.org/.
    There is much more to be said, starting with “Congratulations, you just created an object”, which is… untrue. But I don’t know that further critique would add any benefit to this particular flame…
    I DO think that you should keep writing, because the writing itself is good and thorough. You should, however, get some peer review on the topic.

    • Leigh Kaszick
      Author

      From a technical standpoint I understand what you’re saying, but this tutorial was intended to introduce people to the very basics of objects in JavaScript and how to create them, I didn’t want to get into too much detail and end up discussing prototyping using object literals as ‘classes’ and then creating object instances that inherit from these object literal ‘classes’.

      When I said “Congratulations, you just created an object”, I meant that very loosely to show people just how simple it is to define an object as most people would already be familiar with defining a function.

      I will get into more detail about inheritance in another tute, and hopefully clear up the differences between objects and literal notation. Would be happy for you to proof read it before submission :)

      • http://blog.bogojoker.com Joseph Pecoraro

        I agree with Jeremy. I think you did a good job with the tutorial, covering areas people typically have trouble, but some of the fundamental parts are “hand-waved”. Remember that your audience is developers. If you are going to water down particular sections let them know!!

        The part I found most frustrating was your explanation of “scope” and “this”. To be honest, you provide a good ballpark description to “get the jist of it” but you don’t indicate that there is more to it, or point to a resource where someone can learn it correctly in more detail. To put it in perspective, what is a developer to think when they use jQuery and “this” continually changes seemly magically for them?

        In summary. Be honest/open about simplifications and point to external resources for full disclosure if it may benefit the readers. I can see that you put a lot of work into this article and I appreciate that (I know from personal experience as well). Keep on writing, hopefully we can improve the quality of your articles =)

  • http://joelongstreet.com Joe Longstreet

    Very nice tutorial.

    I went the route of learning jQuery before javascript (because of time constraints). As I work on more complex web applications, I’m starting to notice gaps in my knowledge – especially when I see lots of repetitive code. This tut helped a lot, I’m also reading Crokford’s ‘Javascript: The Good Parts’ – would definitely recommend it

  • http://www.phpandstuff.com Burak

    JavaScript is a surprisingly powerful language most people don’t realize.

  • http://andrewburgess.posterous.com Andrew Burgess

    Great Introduction to Object-oriented JavaScript, Leigh!

    It’s important to note that the new operator is *required* when using a constructor function. If you don’t use it, _this_ in the constructor will refer to the global window object instead of a new object.

    You can also create new objects with Douglas Crockford’s Object.create method:

    if (typeof Object.create !== ‘function’) {
    Object.create = function (o) {
    var F = function () {};
    F.prototype = o;
    return new F();
    }
    }

    This allows you to create a new object that inherits the properties of whatever object you pass in.

    var anotherObject = Object.create(firstObject);

    And changing the value of a property on anotherObject doesn’t hurt firstObject.

    • Leigh Kaszick
      Author

      A tutorial on prototypal inheritance next perhaps? :)

      • http://andrewburgess.posterous.com Andrew Burgess

        Sounds Good!

  • http://sonergonul.com Soner Gönül

    Jquery is the best Javascript library. Thanks..!

  • http://lucassmith.name Luke Smith

    Great to see more “Intro to JavaScript” content showing up on the web. Particularly when it is more informed of best practices.

    One thing to note, however is that scope has nothing to do with ‘this’. this refers to the execution context, which is irrespective of the scope chain. As Crock details in The Good Parts, this is set in one of four ways based on how a function is invoked:

    Function Invocation doSomething()this is window/global
    Method Invocation fooObject.doSomethingthis is fooObject
    Constructor Invocation new SomeClass()this is an instance of SomeClass
    Apply Invocation doSomething.apply(barObject, args)this is barObject

    Where the function is defined affects the scope chain. How the function is executed affects the execution context (this). See http://lucassmith.name/pub/this.html

  • http://spotdex.com/ David Moreen

    OO is the way to go with everything; of course that is just my opinion. OO programming just makes lives easier, read code, edit, and fix bugs faster.

    • Robert

      Surely, the OO approach did become the superior of procedural programming. But still, there are project´s and such where procedural programming will come in handy. And still, most people don’t seem to understand why OOP was invented and totally forget´s about UML and such which will render OOP “useless” in big projects anyway. Also, OO was invented for the need of re-usability. When programming C back in the days, they noticed that they had to rewrite a lot and couldn’t inherit the easy way, thus making it far more complex writing heavier applications. OOP is my way of programming most projects, but I think it has a better place C++ than in PHP as an example…

      • Robert

        Let me re-phrase that a tidy bit: You do not have the same control of what’s going on with memory, PHP is a very loosely typed language. OO is a great approach, but the language is very loose anyway.

    • Robert

      And you seem fairly young (therefor you may have missed out on some experience), you’ve totally forgotten about accesibility on your site dude, give the people with bad vision some title attr and alt’s, and the colors will look wierd when a color-blind looks at the page, just some tips, it’s hard to forget! :) This was just to help you out for future projects, we all need more designers and great developers we do!

      • http://mhuntdesign.com Matthew Hunt

        Agreed. He’s on his way though. There’s a lot to learn in this field.

    • Brian

      Keep in mind that with JavaScript, you’re always dealing with procedural operations, and very loosely defined object oriented constructs. JavaScript works much better as a prototype-based language if you want to build full, large-scale applications. Much of what you see with OO in JavaScript is syntax sugar, including many attempts to imitate classical-based inheritance. The idea of constructors (also as Function objects) confuses the matter greatly, giving you the impression that you have classes. I would suggest to anyone who hasn’t, learn about the prototype features of JavaScript, and how it differs from full-blown OO.

    • James

      Yeah except OO programming in JavasScript is totally different from normal OO programming.

      Where you normally would define a class, a public ( or private ) constructor, and all its methods, you dont do this is JS. So define OO programming then :)

      Instead of defining a class, you prototype everything. Which is totally different then normal OO programming. And in my opinion way better then the “old” way. Too bad there are no real serverside languages which provide a prototyping method.

  • cc

    This tut conflates a class with an object.
    The litetral and ‘constructor’ versions are presented as different syntax for the same thing. In one, however, you have created an object, in the other, defined a class.

    • Leigh Kaszick
      Author

      Yes but unfortunately JavaScript doesn’t really have ‘classes’ so both literal notation and constructors can be used interchangeably as either an object definition or a ‘class’ definition. I merely wanted to present the different ways of creating objects, be it for a class type definition or as a constructor, I’ll leave that up to the programmer. However I do agree that an object literal makes a much better class type object, as in classical languages classes are typically defined and not instantiated.

  • Tim

    Nice job. Read it through and haven’t spotted anything I wouldn’t do. But Shhh! don’t tell everybody how to do it… They’ll all be able to work as efficiently as us!

  • http://viralpatel.net viral patel

    Hey.. Great Tutorial
    Really nice way of learning concepts of Javascript.

    Here is something similar: Object oriented programming using JavaScript

  • http://os.laroouse.com esranull

    güzel bir yazı olmuş

  • http://thx2madre.tistory.com Irene

    Good tutorial!

  • http://blog.tayfunsen.com tayfun

    Nice introduction to JavaScript. Next in the series could be the prototype property of functions.

    In particular, adding methods as object properties (this.whatAmI in the example) is not the optimal way to create objects because each object will have this method created individually. Using prototype you can have this method available to all objects by inheritance. This will be better performance wise and be more suited to the OOP way.

  • http://madeout.blogspot.com gpilotino

    “if you’re inside a method that is within an object, ‘this’ will refer to the object.”,
    well not always.

    ie. if you have a callback defined inside an object “this” will refer to the calling object, not to the one the callback is defined into.

    (that’s the reason sometimes you have to assign “var self = this” and use the alias “self” in the defined callbacks)

    • ManiKanta

      Well!

      Can you explain this with an example

      Thanks

    • Ran

      This is the exact problem I had and which brought me here, and with your post I was able to find the workaround from http://bitstructures.com/2007/11/javascript-method-callbacks , very helpful article that one, though it’s kind of strange how JS would behave in this way, guess you just can’t expect much from a scripting language that doesn’t even support actual classes and forces you to rely on hacky ways in-order to replicate the behaviour of true OOP.

      And this article is nice, but it kind of simplifies things too much and thus leaves out essential information as stated in the other comments already, so won’t get more into that.

  • http://www.kitfoxink.com Kit

    Man oh man. Combine PHP JSON and JavaScript and you have a lot of power behind you.

    Great Tutorial, this definitely makes jQuery make WAY more sense.

  • http://www.diffbtwn.com satya sheel pandey

    good tutorial ,this helps me in my project.Thanks

  • Brian

    Many programmers don’t realize it because they have been falsely led to believe it is only a matter of style, but when you use object literal syntax you are always creating in-memory objects. When you use a constructor, you are not actually initializing an object. Yes, constructors are objects, but only in that they are all prototypes of the Function object in core JavaScript. Keep this in mind when you’re creating large scripts. Loading a massive object literal for a page that only makes use of a portion of it can be unnecessary work for the interpreter. You may be better off using constructors, and initializing objects only when needed.

  • http://adrusi.com Adrian

    The way I see javascript libraries is that you should understand how the library’s object works. in jquery’s case, you should be able to figure out that it starts with a “function $(selector) {” and somewhere in the middle it has “this.animate = function(css, duration) {” and so on, but I don’t see any reason that you should need experience in javacript before using a library. They re easier, faster, and only add a little processing time.

    • http://www.wdonline.com Jeremy McPeak

      You’re certainly free to spend your time however you want, but how do you expect to write effective and efficient code if you don’t know the language? What do you do when you encounter a bug that is caused by the lack of knowledge of the language?

      It’s fine to use a library, but you’re only selling yourself short by being completely and totally dependent on the library.

  • http://imbuzu.wordpress.com ImBuzu

    I just scanned the article. No time to read it whole today, but I’ll soon. I just wanted to point out that theres is yet another way to create objects in javascript. I’ll comment more on that and some other things that I see are missing in the article.

  • http://imbuzu.wordpress.com ImBuzu

    As promised, I’m back to talk a bit more about objects.
    I said there is another way to create objects, and that is using the Object Class (not really a class, but commonly called that way):

    var myObj = new Object();
    myObj.prop = “my property”
    myObj.method = function(){

    }

    As you can see, it is really easy to create objects using the Object “class”. It is basically the same as writing objects using the literal notation.

    One thing I’d have liked to see is usage of the prototype of the constructor function because that is what actually makes a difference between using the constructor and literal notation or Object(). Besides that, I think it is a really good introduction to OO Javascript.

    • Umut

      Can you be able reuse this object. What is the purpose of using this way ?

  • http://ajaxmint.com Raja

    Today I learned the basics of OO Javascript, Thank you for your tutorial.

  • http://www.sebastianjt.com Sebastian Jaramillo T.

    Great concepts. Thanks!

  • http://saiful103a.wordpress.com saiful103a

    awesome tutorial about javascript oop.

  • Minill

    Lucid article on javascript.

  • http://www.andreabarghigiani.info Andrea Barghigiani

    Really appreciated this lesson on OO in JavaScript!
    Now a lot of scripts results more easy to read and understand.

    Ehy Jeff, thanks for the new skills that daily you let it improve!

  • sdaniel

    this ok

  • Bo 3azoz

    Thank u very much Leigh Kaszick for the tutorial… It does help me ;)

    Thank u also Jeremy Martin for the link…

    thank u all Guys ;)

  • Chin Hua

    I guess you should see this. I used it on my new project which make the fun of OO feature in my Javascript code. http://ejohn.org/blog/simple-javascript-inheritance/

  • http://www.bing.com/ Jodi

    mjhvod YATB says you r the best

  • http://www.interlacelab.com Noel

    Save my day.

  • http://www.someshinyobject.com Christopher Walker

    This is the greatest article ever, by the way.

  • Hawk

    Thank you, it’s much better explained than MDC’s “introduction to oop JavaScript” which I found rather confusing and somewhat aimlessly written, at least not so that a beginner like me could understand it. This tutorial here is really good, also a lot of the comments here already are good, thx!

  • Ajay

    From the heading- “Real World Usage…”, i couldnt understood a single thing. I wonder how the other people stated good about the tutorial. Please modify it after that heading.

    -Thanks

  • hari

    Great tutorial for a novice. keep up the good work. This is what i call i perfect heads-up….

  • Sajid Ali

    greeeeeeeaaaaaaaat tutorial i really like it.

    Thanks keep it upp

  • Ramesh

    Nice tutorial! Eagerly waiting for the next chapter!!

  • a77icu5

    what about scope, see this example:

    var myObject = function() {
    this.attr = ”;
    this.method = function() {
    jQuery.getJSON(response) {
    console.log(this.attr); <– show "this.attr is undefined"
    }
    console.log(this.attr); <– no problem
    }
    }

    other problem is that javascript seems not to be sequential, see this example:

    var myObject = function() {
    this.method = function() {
    var result = otherObject.getJsonData(); <– wrapper function of $.getJSON
    jQuery.each(result, function(i, v) {
    //funny code
    });
    }
    }

    javascript don’t wait til getJsonData() return the result and continue to the next line, that’s a big problem because in that case the result always is null, how can resolve this problem? any other solution that using callbacks?

  • Jack

    First off, I must agree with others that this tutorial made it clearer than those at Mozilla Dev Center.

    I do, however, have one question:

    You said,

    “If we’re inside an object, ‘this’ will refer to the object itself however
    if you’re inside a function, this will still refer to the window object…”

    Now it seems to me that an object is declared with a function, so how do we differentiate between ‘this’ within an object (referring to the object) & ‘this’ within a function (referring to the global window object)?

    This is the point at which I wonder if leaving the ‘class’ keyword out of javascript was a good idea.

  • Kelvin

    Awesome and clear tutorial as always. Keep up the good job! Love this site!

  • Brian

    Thanks for the nice article, and for all those above who added constructive criticism.

    As far as learning–and truly understanding OOP, I made my greatest progress by studying/learning Smalltalk. There are a few awesome IDEs available free for download. Beautiful, free implementations. (I really like Cincom’s Visualworks: http://www.cincomsmalltalk.com/main/products/visualworks/). As you probably already know, in Smalltalk, EVERYTHING is an object, derived from a class (including the IDE!). After writing trivial (but incredibly powerful) apps with ST, you’ll have a much better grasp of all the other languages that are only truly partial OOP implementations, C++ included. You don’t have to be a ST pro; just *play* with it for a few weeks, in an IDE “sandbox” where you are continually forced to *think OOP*, at every turn. If you do, you’ll have a huge advantage over those peers of yours who never took the time to actually understand it, totally.
    As mentioned above, the main advantage of OOP is to save time and work–that’s the whole point! Consider the value of UML. Smalltalk–pure OOP–is aesthetically pleasing, as well, as computer programming languages go. Smalltalk is actually a *fun* language. Go get some, then come on back to all the other half-baked attempts at OOP that will seem to be cobbled together with bailing wire (OK, I exaggerate). After learning pure OOP, going back to JS and other partial OOP implementations might seem a little frustrating, because what is essentially a group of simple, cohesive, obviously logical concepts naturally becomes more complicated and less comprehensible, (i.e., the logic underpinnings), to the programmer with less-than full implementations.
    Anyway, I’m just an amateur. I hope I’ve added something meaningful to the conversation.
    I learned more about JS OOP from your tute. Thanks, again!!!

  • Leigh Kaszick

    I have re-read the section about ‘this’ and I realised why what I wrote is confusing. It was one of those things that’s you write while knowing what is going on inside your own head and not reading it from another persons perspective :p

    I believe what I should have written was:

    When you reference ‘this’ outside of a function or an object you are still inside the global object and therefore referencing the window object. If you’re inside a function (this is where I lost most people) that is defined within the window (global) object then ‘this’ will still refer to window. However if you define a method inside an object and then instantiate that object, ‘this’ will refer to that instance of the object. Similarly if you define a “static” object (an object which isn’t instantiated) then ‘this’ will still reference that “static” object when used within that object (e.g within a method of that object).

    function myFunction(){
    return this; // window
    }

    var myStaticObject = {
    myMethod: function(){
    return this; //myStaticObject
    }
    }

    var myObject = function(id){
    this.id = id;
    }

    myObject.prototype = {
    id: “foo”,
    getId: function(){
    return this.id;
    }
    }

    var instanceOfMyObject = new myObject(“bar”);
    instanceOfMyObject.getId(); // “bar”

  • http://www.bixbite.org devu

    Nice article.

    Did you even consider test witch method is actually better in terms of performance?

    Here is the test:

    http://jsperf.com/js-and-oop/2

    • Christian

      I don’t believe that is a fair comparison b/c in the constructor example you have yet to instantiate anything.

  • http://www.meomar.info Omar ALi

    Clean and simple :)

  • santen

    nice article, thank you for posting!

  • Deva Karthik

    Really good one!

  • sapna

    Got a clear idea of creating objects in javascript. Great post. Keep writing. :)