Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Working with objects and prototypes

From: JavaScript Essential Training

Video: Working with objects and prototypes

In this course, we have covered creating date objects. We have covered creating array objects and regular expressions, and these are all built-in and predefined objects in JavaScript. And we've even talked about how to make our own simple objects, which we start off by just creating new variables that are wrapping several other variables together under one name. But we can go deeper with this idea, and for those of you who are interested in going deeper, particularly if you're coming from another object-oriented language, here's a quick introduction to the concept of a prototype in JavaScript.

Working with objects and prototypes

In this course, we have covered creating date objects. We have covered creating array objects and regular expressions, and these are all built-in and predefined objects in JavaScript. And we've even talked about how to make our own simple objects, which we start off by just creating new variables that are wrapping several other variables together under one name. But we can go deeper with this idea, and for those of you who are interested in going deeper, particularly if you're coming from another object-oriented language, here's a quick introduction to the concept of a prototype in JavaScript.

First, what can be a source of confusion is that there is a popular JavaScript library called Prototype, but that's not what I am talking about here. I'm talking about the prototype built-in language future of JavaScript which will help us create more formalized objects. So what is the problem anyway? Well, a quick recap. We can create an object by using the curly braces, or by using the words new object, and in this case I'm using the curly braces and I am loading it with some initial values.

After this, I have this playerFred variable that I can use, and I can add new properties freely to him. Properties are variables that belong to this particular object, and I can even add methods, which are functions that belong to this object, and then call the methods of that object. But there is nothing that would stop me, for example, from creating another object which looks like it should have a similar structure, but in this case would have high score instead of score and have level instead of rank. It just doesn't match the general structure.

And this is what usually makes programmers coming from other object-oriented languages shudder because they want to define multiple objects that share the same description, and we can do this here. We can formalize our own objects. Now, for those of you coming from those other languages, no, we don't get classes in JavaScript, but we can kind of fake it. So how do we do this? Well, step one, we create what's called a constructor function to make our new objects. That really means we create a function as normal with the name that we want to use to create multiple objects from, in this case Player, and by convention we use an uppercase first letter when defining this, the same way that Date is an uppercase D and Array is an uppercase A and Regular expression has an uppercase R.

Then step two is we create a new variable using the normal camelCase idea and importantly, we use the word new to create a new variable from that Player constructor. Now this will often seem a little odd the first time you see it. We have only seen the word new used before with built-in JavaScript objects like Date and Array and Regular expression, but no, we can claim it ourselves. This creates a new object and calls this constructor function for this new object.

Now, there is nothing in this constructor function right now, so we might want to add a little data to the object. Well, I could put the phrase this.name=fred. If you remember, "this" is a word that we can use to refer to whatever the current object is, but I don't want to make all my objects have a name of fred, so well, here's where we use the benefit that this is a function. So what we can do instead is make this constructor function take a parameter, in this case we will call it n, and then when we call it we will actually create a new player passing in the name Fred.

In this case, it will call the function Player and set the current object's name to Fred. So we now have an object with that property inside it. I could then call it again, creating another new player object, but in this case I'm creating a new object called Bob with the Bob property set inside it. So this is how I start to formalize my objects a bit more than I could before. So if I switch over to a very simple piece of JavaScript where I'm doing exactly that, I have a constructor function here and I'm calling it once using the new keyword to create this as an object.

In fact, if I want to give this object a bit more in the way of properties, I am going to do it internally here. We are going to have a this.score = s and a this.rank = r, and I will make this function accept three parameters. Now, hopefully this will make a kind of sense. We are really just calling it like a normal function, passing in three parameters. But the most important piece is what I am going to do next, which is that every object in JavaScript has what's called a prototype property, and functions like the Player function I have just made is an object in JavaScript, and I can use that prototype property.

What I can do is call Player.prototype. and then use this to attach to tie new functions to this player object. So I might decide that I want this object to have a method called logInfo. Now, this is completely up to me what I call it. I'm going to set that equal to and give it a function body here, and all I will do with this one is make it write out of console.log that writes out the message "I am" then a comma and then this.name, again, using this to say whatever the name property of the current object is, because we might call this with 500 different objects.

I want to make sure it writes out the right one for each one. I could add another one in here. Keeping the same general format, I am going to say Player.prototype. Well, let's give this one a promote method and when promote is called it's going to say this.rank++. Add 1 to whatever the rank property of the current object is, and then we will write out a message that says, "My new rank is: this.rank." And using prototype I am attaching these functions to that constructor so it means they'll automatically be available on any object that was created using that new keyword.

So down here after I create this new variable called Fred, which is a new player, I can say fred.logInfo, fred.promote. Save that, jump over and open up the page that's using this script. If I have Firefox open--yup I do-- I can see in the Console here "I am: Fred," "My new rank is: 6." Now it seems like an awful lot of trouble if I was just going to create one thing, but of course the whole benefit of this is I can now create a new variable called Bob which is a new player, and I will pass in three pieces of information--the name, the score and he rank--and I don't have to do anything else to make this object have the logInfo method.

It will automatically have it. Same way it will have the promote method. I can just start calling those. Save that, jump over into the browser, refresh that, and we are getting information about the different object. Create a third one, create a fourth one, create a fifth, and so on. Each of them will act independently of each other. They will know about their own properties and they will base everything that they can do on both this constructor and any of these methods that I've attached using the .prototype property, without having to separately attached them for each and every object.

Now, we are still in JavaScript, and it is a super-flexible language, so I could still dynamically start adding extra methods and properties to each individual object, but I don't need to here. Now as you might expect, you can take these idea of prototypes and of object orientation in JavaScript much deeper than this, but that's a subject for a completely different class. So for those of you looking for a somewhat more formalized object-oriented structure, this is certainly how you might begin.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 107279 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.