0
0
Javascriptprogramming~5 mins

Constructor functions in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a constructor function in JavaScript?
A constructor function is a special function used to create and initialize objects. It sets up properties and values for new objects using the new keyword.
Click to reveal answer
beginner
How do you call a constructor function to create a new object?
You call a constructor function with the <code>new</code> keyword before the function name, like <code>const obj = new MyConstructor();</code>. This creates a new object and runs the constructor code.
Click to reveal answer
beginner
What does the this keyword refer to inside a constructor function?
Inside a constructor function, this refers to the new object being created. You use this to add properties or methods to that new object.
Click to reveal answer
intermediate
What happens if you forget to use new when calling a constructor function?
If you forget new, the constructor function runs like a normal function. this will not point to a new object, which can cause errors or unexpected results.
Click to reveal answer
intermediate
How can you add methods to all objects created by a constructor function?
You add methods to the constructor's prototype. For example, MyConstructor.prototype.sayHi = function() { console.log('Hi'); };. All objects created will share this method.
Click to reveal answer
What keyword do you use to create a new object with a constructor function?
Anew
Bcreate
Cobject
Dconstruct
Inside a constructor function, what does this refer to?
AThe constructor function itself
BThe global object
CThe new object being created
DUndefined
What happens if you call a constructor function without new?
AIt returns null
BIt throws a syntax error
CIt creates a new object anyway
DIt runs as a normal function, <code>this</code> is not the new object
How do you add a method shared by all objects created by a constructor?
AAdd it to the constructor's prototype
BUse a global variable
CAdd it to each object manually
DAdd it inside the constructor function
Which of these is a correct constructor function name by convention?
Aperson
BPerson
CpersonConstructor
DcreatePerson
Explain how a constructor function works in JavaScript and how you create an object with it.
Think about how you make a new object and set its properties.
You got /3 concepts.
    Describe how to add a method that all objects created by a constructor function can use.
    Where do you put methods so all objects share them?
    You got /3 concepts.