constructors Flashcards
https://css-tricks.com/understanding-javascript-constructors/ https://content.pivotal.io/blog/javascript-constructors-prototypes-and-the-new-keyword
Constructors are like regular functions, but we use them with the _______ keyword
new
There are two types of constructors
- built in
2. custom
It’s a convention to ____________ of constructors to distinguish them from regular functions
capitalize the name
function Book() { // unfinished code }
var myBook = new Book();
myBook instanceof Book //
true
function Book() { // unfinished code }
var myBook = new Book();
alert(myBook.constructor !== Book);
false
constructor points to Book
var s = new String("text"); s.constructor === String; // "text".constructor === String; //
true
true
var a = new Array(); a.constructor === Array; // true
[].__________ === Array; // true
constructor
Although the constructor property can be used to check the type of an instance, it is generally recommended to only use the instanceof operator for this purpose
TRUE / FALSE
TRUE
to check the type of an instance use instanceof or constuctor
WHY?
instanceOf
because the constructor property might be overwritten. As a result it’s not a reliable method for checking the type of an instance.
A getter is expected to___________, while a setter receives the value being assigned to the property as an argument.
return a value
The JavaScript language has _______ built-in constructors
9
Object(), Array(), String(), Number(), Boolean(), Date(), Function(), Error() RegExp()
Object literal notations are preferred to constructors
TRUE / FALSE
TRUE
It’s important to remember to use the new keyword before all constructors. If you accidentally forget new, you will _______
be modifying the global object instead of the newly created object
vehicle; // {}
var FuzzyBear = function FuzzyBear() { }; vehicle.constructor = FuzzyBear;
vehicle; // { constructor: function FuzzyBear() }
vehicle.constructor == FuzzyBear; //
vehicle instanceof FuzzyBear //
vehicle instanceof Vehicle //
true
false
true