Learn JavaScript - Constructor Functions

Question Click to View Answer

Create a sally object with first_name, last_name, and full_name properties with object literal notation, similar to the following example.

var bob = {
  first_name: "Bob",
  last_name: "Lob",
  full_name: function () {
    return this.first_name + " " + this.last_name
  }
}
var sally = {
  first_name: "Sally",
  last_name: "Mae",
  full_name: function () {
    return this.first_name + " " + this.last_name
  }
}

The sally_object is similar to the bob object and it was tedious retyping all this code to create a separate object with the same behavior. In this quiz, constructor functions are introduced to facilitate the creation of similar objects.

The following code illustrates how to define a constructor function and use the constructor function to create an object.

function Mammal() {
  this.warm_blooded = true;
  this.scaly = false;
}
var fido = new Mammal();

Print the scaly property of the fido object to the console.

console.log(fido.scaly);

Constructor functions are specialized JavaScript functions for creating objects. Notice that the fido object could also be created with object literal notation.

Use object literal notation to create an object assigned to the spot variable, similar to the following constructor function.

function Mammal() {
  this.warm_blooded = true;
  this.scaly = false;
}
var spot = new Mammal();
var spot = {
  warm_blooded: true,
  scaly: false  
}

Constructor functions and object literal notation can both be used to create JavaScript objects. Constructor functions are better when multiple similar objects are created, but both object construction techniques can be used to make JavaScript objects.

Call the square() method on the my_calculator object.

function Calculator() {
  this.square = function (x) {
    return x * x;
  }
}
var my_calculator = new Calculator();
console.log(my_calculator.square(5));

Constructor functions can create objects with methods. All objects created by the Calculator constructor in this example have a square() method.

Use object literal notation to create an object that has the same behavior as the objects created by the following constructor function.

function Calculator() {
  this.square = function (x) {
    return x * x;
  }
}
var my_calculator = {
  square: function (x) {
    return x * x;
  }
}

Constructor functions are just specialized functions that can be used to create the same objects that are created with object literal notation.

Create an object with the Person() constructor and then call the full_name() method.

function Person(first_name, last_name) {
  this.first_name = first_name;
  this.last_name = last_name;
  this.full_name = function () {
    return this.first_name + " " + this.last_name
  };
}
var crazy_pants = new Person("crazy", "pants");
console.log(crazy_pants.full_name());

The arguments that are passed to the Person() constructor function are used to create properties of the object.

Notice that the "this" keyword refers to the object that is being created in constructor functions. In the full_name() method of the constructor function, this.first_name and this.last_name refer to properties of the person object that is being created by the constructor function.

Use object literal notation to create an object that behaves similarly to the wilson object that is created with the following Person() constructor:

function Person(first_name, last_name) {
  this.first_name = first_name;
  this.last_name = last_name;
  this.full_name = function () { return this.first_name + " " + this.last_name };
}

wilson = new Person("wilson", "rawls");
var wilson = {
  first_name: "wilson",
  last_name: "rawls",
  full_name: function () { return this.first_name + " " + this.last_name }
}

Notice that it would be much easier to make 100 person objects using constructor functions compared to object literal notation. Object literal notation is great if only one object of a specific type is being made, but constructor functions are superior if many objects of a given types will be made.

What does the following code print to the console?

function Hat() {
  var brand = "shhh can't tell";
}
var my_hat = new Hat();
console.log(my_hat.brand);
undefined

brand is a private variable in the Hat() constructor function, so it can only be accessed by functions within the constructor function. Remember that JavaScript functions have function scope meaning that variables defined in the function are only available within the function itself.

What does the following code print to the console?

function Hat() {
  var brand = "shhh can't tell";
  this.getBrand = function () { return brand; };
}
var my_hat = new Hat();
console.log(my_hat.getBrand());
"shhh can't tell"

The brand variable cannot be directly accessed outside of the Hat() function. However, the brand variable can be accessed anywhere within the Hat() constructor function. The getBrand() method can access the brand variable and make it indirectly accessible.

The prototype property of constructor functions can also be set to add methods to objects created by constructor functions. JavaScript functions are objects and the prototype property can be used to add methods to the objects that are created by constructor functions.

function Dog(name) {
  this.name = name;
}

Dog.prototype = {
  constructor: Dog,
  bark: function () { return "ruff ruff" }
}

var rover = new Dog("red rover");
console.log(rover.name);  // returns "red rover"
What does the following line print to the console?
console.log(rover.bark());
"ruff ruff"

The prototype design pattern is used to JavaScript to give methods to objects created by constructor functions.

Type the "this" keyword into the JavaScript web console of your favorite browser (hopefully Chrome or Firefox) and explain what is returned.

this  // the window object is returned

The global object is created when the JavaScript interpreter starts and it creates global properties (i.e. NaN), global functions (i.e. parseInt()), built-in constructor functions (Array()), and global objects (Math). The global object for client-side JavaScript is called window.

What does the following line return when typed into the JavaScript web console of an internet browser?

this === window
true

window is a keyword that refers to the global object. this refers to different objects in different contexts, but it refers to the window object in the top level namespace.

Invoke the zombies function.

function zombies() {
  return "We like to eat people";
}
zombies();

Invoking a function is just a fancy way to say "running a function" or "executing a function". JavaScript functions are invoked by adding () to the end of the function name.

What is the difference between the whatever() and best_quote() functions in the following code?

function whatever() {
  return "talk to the hand";
}

var clueless = {
  best_quote: function() { return "That’s Ren and Stimpy. They’re way existential." }
}

whatever() is a function in the global namespace. best_quote() is a property of the clueless object, so it is a special type of function called a method. When whatever() and best_quote() are invoked, they are said to have different invocation contexts because they are called in different ways. whatever() is invoked as a function and best_quote() is invoked as a method.

What does the following code print to the console?

function sampleFun() {
  console.log(this);
}

The global window object

The this keyword has different values depending on when it is used. When the this keyword is used in a function that is invoked in a function context (meaning the function is not part of a constructor function or the property of an object), then the this keyword refers to the window object. The this keyword is rarely used for functions that are invoked in a function context.

What does the following code print to the console?

var an_object = {
  hat: function() { return (this === an_object); }
}
console.log(an_object.hat());
true

The hat() method is bound to an_object and the this keyword within the hat() method refers to an_object.

What does the following code print to the console? Explain the use of the "this" keyword.

var honeyBadger = {
  personality: "vicious",
  modusOperandi: function () {
    return "I am " + this.personality + " because I don't care!";
  }
}
console.log(honeyBadger.modusOperandi());
"I am vicious because I don't care!"

Notice that the "this" keyword in the modusOperandi() method refers to the honeyBadger object. When functions are invoked as methods, "this" refers to the object that defines the method.

What does the following code print to the console?

function Raisin() {
  this.formerSelf = "grape";
  this.goodness = function (number) {
    return "I am " + number + " times worse than when I was a " + this.formerSelf
  };
}
var r = new Raisin();
console.log(r.goodness(10));
"I am 10 times worse than when I was a grape"

When functions are invoked as constructors, the "this" keyword refers to the object that is being created. In this example, we are creating an object that is assigned to the r variable. The "this" keyword in the goodness() function refers to the object that is assigned to the r variable.

What does the following code print to the console? Explain the use of the "this" keyword.

function Whiteboard() {
  this.purpose = "brainstorm";
  this.businessReason = function () {
    return this.purpose + "…..profit!!"
  }
}
var w = new Whiteboard();
console.log(w.businessReason());
brainstorm..profit!!

The businessReason() method uses the "this" keyword to refer to the object that is being created by the constructor function and is assigned to the variable w in this example.

What does the following example print to the console?

console.log((function (x, y) { return x + y })(3, 4));
7

The anonymous function in this example is defined and invoked on the same line. JavaScript functions are frequently invoked immediately after they are defined, so be prepared to see this technique used frequently.

What does the following example print to the console?

var globalObject = window;
function nestedExample() {
  function innerFunction () {
    return this === globalObject;
  }
  return innerFunction();
}
console.log(nestedExample());
true

Due to a design flaw in the language, inner functions use the function invocation context, not the method invocation context, so the value of "this" in the innerFunction() equals the globalObject. Additional quirks and complicated features of the JavaScript language will be covered in subsequent quizzes.

Create a constructor function called Square() to create square objects with a side property and a method to calculate the area. Use the Square() function to create a square object.

function Square(side) {
  this.side = side;
  this.area = function () { return this.side * this.side };
}

var my_square = new Square(4);  // creates a square object
my_square.area();  // returns 16
my_square.side;  // returns 4

Create an Employee() constructor function with days_worked, vacation_days_per_year, and vacation_days_taken properties. Add a vacation_days_left() method that returns the number of vacation days the employee has remaining.

function Employee (days_worked, vacation_days_per_year, vacation_days_taken) {
  this.days_worked = days_worked;
  this.vacation_days_per_year = vacation_days_per_year;
  this.vacation_days_taken = vacation_days_taken;
  this.vacation_days_left = function () {
    return(this.days_worked / 365 * vacation_days_per_year - vacation_days_taken);
  }
}

var sally = new Employee(180, 20, 4);
console.log(sally.vacation_days_left());

Create a Circle() constructor function to make circle objects with an area method. Add a private PI variable to the circle objects that are created a set its value equal to 3.14.

function Circle(radius) {
  var PI = 3.14;
  this.radius = radius;
  this.area = function () { return PI * Math.pow(this.radius, 2) };
}

var my_circle = new Circle(5);
console.log(my_circle.area());

Explain what the following code prints to the console.

function pirate () {
  return this;
}
console.log(pirate());

The pirate() function returns the global window object. The global window object is created by the JavaScript interpreter when it is started to store built-in constructor functions, global constants, and global properties. When functions are invoked as functions (i.e. they are in the global namespace and are not part of an object or constructor function), the value of the this keyword is the global object.

Demonstrate that the this keyword equals the global object for functions that are invoked with function invocation context.

function exampleFunction() {
  if (this === window) {
    return "this equals the global object with function invocation context";
  }
}
console.log(exampleFunction());

Functions that are not properties of an object and are not constructor functions are invoked in the function invocation context.

Demonstrate that the this keyword refers to the object itself for functions that are invoked in the method invocation context.

var cup = {
  something: function() {
    return this === cup;
  }
}
console.log(cup.something());  // prints "true" to the console

Demonstrate that the this keyword refers to the object that is being created for functions that are invoked in the constructor invocation context.

function Paper() {
  this.whatever = "ok";  // "this" refers to the object that is created by the Paper() function
}
var my_paper = new Paper();
console.log(my_paper.whatever);  // The object created by the Paper() constructor function has a whatever property.  In the body of the constructor function, the "this" keyword refers to the object that is being created and referring to "this" allows properties to be added to the object that is being constructed.

What does the following code print to the console?

console.log(function () {
  return "Hey hey hey";
}());
"Hey hey hey"

Notice that the function is defined and invoked in a single statement.