In today’s tutorial, we will learn how to create a Method in a Custom Object. Let’s say we wanted a group of variables, organized within one category (or object), this way we can organize and separate all of the variables in our code. By doing we can create methods and these method will contain a function with logic which can then be called easily later on when coding.

Creating Custom Objects

Custom objects are simply a list of variables contained within a category. To contain these categories, we use the ({}) brackets. Here is an example.

As you can see, we can make a list of variables within our Custom Object and store a String or even a function within that variable. How do we display these variables? Easy. This variables now become Methods which are executed naming the Object and Method name like so :ObjectName.VariableName. As an example we will call each method:

This makes it easier to reference back to these variables or use them for later.

Using Custom Objects and Methods Example

Lets say we want to greet the user with a friendly message and to input their name. We will add logic so the computer knows if a name was inputed or was canceled. Last it will us the name and state it’s own name from another custom object we created. Let’s give it a try.

Let’s look over what we created. We created an Object called “Questions” with Variables “name” and “intro”. At any point we can use or Questions.intro and use them as methods. We also created a global variable object called smartBot that contains the object’s name. Simple so far but adding the logic is tricky. The intro method will contain a function that will tell the computer to prompt the user and validate their answer. We provided a conditional to do so.

We start the program by executing the alert function which will display the “Questions.intro”. As you can see, by using the .call() method, we are able to break our of the currently running function and us “this” to reference a different variable (namely the global name variable that is A nice little trick to break out of the function and replace with different data.


Although this may not be the most conventional approach for a conditional prompt, it is always good to know the different ways you can create Javascript code. Start practicing different ways of using customs objects and the methods you create out of them to get different and more coding efficient results.