Javascript Flashcards
How many types of number does Javascript have?
A single number type (represented by a 64bit float internally)
Is NaN equal to NaN?
No - it is equal to nothing else, therefore the only way to test for it is to use the function isNaN(number)
In Javascript, is ‘C’ + ‘a’ + ‘t’ === “Cat”?
Yes
Do strings have methods?
Yes - think of things like String1.toUppercase();
In Javascript do blocks create new scope?
No - so variables should be declared at the top of a function
What values typically evaluate to false?
false, null, undefined, ‘’, 0, NaN
What does the string ‘false’ evaluate to in Javascript
True
What is the ‘for in’ structure in Javascript?
A for loop.
for (var myvar in obj) { // Loop through }
What is a label in a break statement?
You can break to another location (labelled by label). i.e.
break myLabel;
What are the simple types in JavaScript?
numbers, strings, booleans, null and undefined
Are numbers, strings and booleans objects?
No - but they do have methods
Objects in JavaScript are…
Mutable keyed collections
Do you need to have a class in JavaScript to create an object?
No, objects in JavaScript are class free.
What is an object literal?
A pair of curly braces surrounding zero or more name/value pairs. i.e.
var empty_object = { };
var stooge = {
“first-name”: “jerome”,
“last-name”: “Howard”
};
What names must be enclosed in quotes in an object literal?
Names that don’t conform to normal variable naming conventions.
How do retrieve a variable from an object literal?
Using the [ ] operator
myObj[“name”]
How can you fill in a “default” value when assigning a value from an object literal?
var val = obj[“first-name”] || “(none)”;
(i.e. it will either provide the first-name element of the object or “(none)”
What happens when you try to retrieve values from “undefined”?
Throws a TypeError exception.
How do you prevent JavaScript throwing an exception when you accidentally try to access an element of an object that is undefined?
Use the && operator
flight.equipment // undefined
flight.equipment.model // throw “TypeError”
flight.equipment && flight.equipment.model // undefined
(I guess it fails on the left hand operand like other languages and doesn’t execute the right hand operand)
Objects in Javascript are passed by…
reference
What does setting “defer” on a script tag do?
It indicates to the browser that the script can start downloading immediately, but it wont’ be run until the page is loaded. It should only be used when using external
How would you specify the defer attribute in XHTML?
defer=”defer”
What is the async attribute used for?
To specify that a script can be run as soon as it is loaded (not wait for the page)
What is the potential issue with having multiple external scripts labeled as async?
They may run out of order, so there should be no dependancies between them.
What options are available to prevent code being interpreted as HTML when embedding javascript in XHTML?
Use the html codes for > or < signs (or they will be interpreted as tags) - or use < ! [CDATA [ block
What is quirksmode?
It was a mode that IE used in version 5.5 - turning it on made it behave like I.E. 5 (non-standard) and switching it to standards mode (5.5) made it behave in a more standards compliant way.
In ANY browser, how do you turn off quirksmode?
By adding a correct doctype. (i.e. HTML 4.01 strict, XHTML or HTML5)
In ANY browser, how do you enable “almost standards mode”?
By using the transitional and frameset doctypes
What is the only only element that can be included in the body tag, but not in the noscript tag?
script
How do you inform a user that they require a javascript enabled browser?
By using the noscript tag < body> < noscript> < p>You require Javascript dude </> < /noscript> < / body>
The first letter of a Javascript identifier must be…
a letter, an underscore or a dollar sign
How do you enable strict mode in Javascript?
Place
“use strict”
at the top of the script
Is it possible to leave out the ‘;’ in a statement?
Yes - although not recommended.
Variables in javascript are ….. typed.
Loosely
Is the following valid? var message = "hi"; message = 100;
Yes - but not recommended (you are changing the type of the variable, which could be confusing)
What is the difference between using var and not using var to declare a variable?
Using var makes the variable local to the block. I.e.
function foo() { var message = "Hi"; }
message will be destroyed when execution leaves that function block.
Global variables (declared without using var) are not recommended - how do you detect their use in your code?
By setting “use strict” on the script, a ReferenceError will be thrown
How do you declare multiple variables in a single line?
var message = "hi", found = false, age = 29;
If you have received the following the error - what happened?
Uncaught SyntaxError: Unexpected eval or arguments in strict mode
You declared a variable named eval or arguments in strict mode (which is not allowed).
What operator do you use to determine the type of a variable?
typeof varName;
What results does typeof return?
undefined boolean string number object function
Functions are considered …… in ECMAscript?
objects (although they have some unique properties to themselves)
If a variable is declared using var and not assigned anything, what is it’s value?
undefined
Should you ever explicitly set the value of a variable to undefined?
No - setting them to null is fine - but not to undefined
How do you convert a variable to a boolean type?
Use the boolean casting function
Boolean(var);
What types are converted to true if passed to the Boolean function (and consequently an if statement)?
true
Any non-empty string
Any non-zero number including infinity (negative numbers too)
Any object
What types are converted to false if passed to the Boolean function (and consequently an if statement)?
false (empty string) 0, NaN null undefined
Is this a valid octal number? var octalNum2 = 079;
No - there is a number 9 in there, which is out of range for a valid octal number - the 0 will be discarded and the number will be 79
Is this a valid octal number? var octalNum1 = 070;
Yes - the leading 0 is important to tell Javascript that this is an octal number (and the numbers are within range (0-7))
Numbers using octal or hex format are treated as ….. in all artithmetic operations?
decimal
There is only one numeric type in Javascript (number) how do you define a floating point number?
Just give it a decimal. var floatNum = 1.1;
ECMAScript always looks for ways to convert floats back to ints, why is that?
They take twice as much memory as an int.
How do you determine the smallest and largest numbers that can be represented in ECMAScript?
Number.MIN_VALUE;
Number.MAX_VALUE;
What does the following expression return?
NaN == NaN
False (NaN is not equal to ANYTHING)
How do you test if a number is NaN?
isNaN(variable);
What happens if you apply isNaN to an object?
The objects method “valueOf()” is called, if that doesn’t work, then it calls the “toString()” method
What are the three functions used to convert non-numeric values to numbers?
Number()
parseInt()
parseFloat()
What unary operator works the same way as the Number() function?
Unary +
What is wrong with the following statement - and how would you fix it?
parseInt(“070”);
The user may be intending 070 to be parsed as an octal number. However, it will be parsed as a string and give 70. To fix it pass parseInt the radix
parseInt(“070”, 8);
What is the difference between parseInt and parseFloat?
There is no radix mode as parseFloat only ever parses decimal values.
Are strings mutable or immutable in ECMAScript?
immutable
How do you convert a value to a string?
Most values have a .toString() method -
var age = 11;
age.toString();
Or add an empty string to it…
age + “”;
NOTE: When used on a number, you can pass it the radix of the value to convert to binary etc.
What does the hasOwnProperty method do on an object?
Checks to see if the method being queried exists on that object, and not part of a prototype
What are the base methods for an object in ECMAScript?
constructor hasOwnProperty(propertyName) isPrototypeOf(object0 propertyIsEnumerable(propertyName) toLocaleString() toString() valueOf()
(All objects have these in ECMAScript)
What happens in this instance?
var stringNum = “1”;
++stringNum;
stringNum is converted to a string then incremented.
What happens in the following instance? var stringNum = "1"; var num = +stringNum;
The value of stringNum is converted to a number and assigned to num.
Can the order that object properties appear in a “for-in” statement be predicted?
No, object properties are unordered in ECMA script
What is the ‘with’ statement?
A convenience statement, it basically negates the need to explictly call an object repeatedly in a given block of code // NOTE: search, hostname and href // are properties of location with(location) { var qs = search.substring(1); var hostname = hostname; var url = href; }
When is using the with statement invalid and an error?
In strict mode, it is not allowed (NOTE: It also has a negative impact on performance, and makes debugging difficult) - not good in production code
What data types does switch work with in ECMA Script?
All data types, including expressions, i.e.
case num > 0 && num <= 10:
How do you access the arguments passed to a function?
ECMA Script has an ‘array’ like structure that can be accessed in the function called ‘arguments’. Use length to find out how many arguments.
arguments.length;
Is function overloading possible in ECMA Script?
No - if two functions have the same name, the final function is the one used.
What is wrong with the following code? var name = "Steveybigs"; name.age = 27;
You can’t add properties to a primitive type (strings are primitives in Javascript) - Note, you wont get an error, but accessing name.age is undefined.
What is wrong with the following code? var person = new Object(); person.name = "Bill chumpbucket";
Nothing - it is perfectly valid to add properties to an object (reference type) in Javascript.
var obj1 = new Object(); var obj2 = obj1; obj1.name = "Dickhead"; alert(obj2.name);
What will be printed out
Dickhead. Because obj2 and obj1 now point to the same object, adding the property ‘name’ on either obj2 or obj1 results in it being accessable from either variable.
All function arguments are pass by…
value
function setName(obj) { obj.name = "hershey"; obj = new Object(); obj.name = "Greg"; } var person = new Object(); setName(person); alert(person.name);
What will be printed?
“hershey”. Remember, variables, even objects are passed by value, not by reference.
You can of course change the properties of an object as if it were pass by reference, but that’s because what is passed is a COPY of the objects reference. Not the actual reference (so internals can be changed by reference, but you can’t change the actual object because it’s a copy, not the actual reference).
typeof can be used to determine what type a variable is - but why isn’t it useful for reference types?
Because it will simply tell you it’s an object. To determine specificaly what type of object, use instanceof.
alert(person instanceof MyObject);
What is the execution context?
It determines what other data a variable or function has access to, as well as how to behave.
In a browser, the global context is said to be…
the window object
(so all global variables and functions are created as properties and methods of the window object.
When a function is executing, it’s context is pushed onto…
the context stack
and it is popped when finished, returning the context to the previously executing context
What is a scope chain?
When code is executed in a context, a scope chain of variable objects is created. It always starts at the variable object of the context whose code is executing and works it’s way back to global scope. This is then used to resolve usage of variable names, starting at the closest scope and working its’ way back to global scope.
In c, the iterator variable in a for loop is local to the for loop - what about Javascript?
No - it’s available outside the for block, as Javascript does not have block level variable scope.
When a variable is declared, it is added to the most immediate context, in the case of a ‘with’ block - what is the most immediate context?
The containing functions local scope.
Why is it important to break the link between a native javascript variable and a DOM object when it is no longer used?
Because DOM objects use reference counting. Javascript uses mark and sweep. DOM objects with Javascript objects can lead to circular references.
Use null to sever the connection.
Is a reference type a class?
No - there are no classes in ECMAScript
Why are Object reference types so useful?
They can be quickly created and have properties added - useful for passing data around in a program quickly.
Define an object literal named ‘person’ with properties name and age.
var person = {
name : “Jizzbomb”,
age: 29
};
What is potentially different with the way you declare properties when using object literal notation?
You can use strings and numbers as the identifiers.
Write an object literal statement that is the same as: var person = new Object();
var person = { }; // Not really recommended
What is unusual about constructor behavior when defining an object via object literal notation?
The constructor is never called.
How would you use an object literal to pass data to a function?
function displayInfo(args) { /* do stuff */ } displayInfo({ name: "Foobaz", age: 20 });
What is the difference between
person[“name”] and
person.name
Nothing - they effectively do the same thing.
What is the advantage of using bracket notation when accessing properties in an object?
You can pass variables into the brackets.
What makes an array different in ECMAScript compared to other languages?
Each slot can hold it’s own data type
Write five different ways to create an array in ECMAScript?
var myArray = new Array(); var myArray = new Array(20); // Set the size var myArray = new Array("Red", "yellow", "Green"); var myArray = Array("Greg"); // You can ommit the 'new' var myArray = ["red", "blue", "Green"];
Is this a valid way of creating an array? var values = [1, 2, ];
Yes, but AVOID it, as it creates an array with 2 OR 3 elements (note the trailing comma) depending on browser. And the last item MAY be undefined.
What is similar about creating objects and arrays using the literal notation?
The constructors are not called for either.
var color = [“red”, “Yellow”, “Blue”];
How do you get the length of the array?
var len = color.length;
Is it valid to set the length property of an array?
Yes, you can remove items by doing something like: var colors = ["red", "Yellow", "Blue"]; colors.length = 2;
What is wrong with this code?
var colors = [“Red”, “Blue”, “Yellow”];
colors.length = 2;
alert(colors[2]);
colors[2] refers to the third element which no longer exists thanks to the color.length = 2 statement;
Write a statement that adds a new color to the end of an array called colors.
colors[color.length] = “Aubergine”;
How do you determine if an Array is an Array?
Array.isArray(value);
Available in IE 9+, FF4+, S5+ O10.5+ and Chrome
What is the difference between toString and valueOf when called on an Array?
Nothing - they both return comma-seperated string containing the values of the array.
How could you simulate the output of Array.toString with the join method?
myArray.join(“,”);
How could an Array be used to behave like a stack?
The Array object contains methods like push and pop which makes it behave like a LIFO object.
What functions allow an Array object to behave like a Queue?
push and shift
How would you sort a basic numeric array?
myNumArray.sort(compare); // Were compare is a user defined comparison function
What is the issue with using just ‘sort’ with no user defined comparison function on a numeric array?
The numbers are sorted as strings, which means they will be out of numeric order.
Write a simple, but fast compare function that works for numeric arrays?
function compare(num1, num2) { return num2 - num1; }
How could you use concat to add an array literal to an existing array?
var myColors = ["red", "green", "Blue"]; myColors = myColors.concat(["purple", "black"]);
What does the slice method do on an array?
Using slice you can copy a section of an array var myArray = [1, 2, 3, 4, 5]; myArray = myArray.slice(1); // 2, 3, 4, 5 myArray = myArray.slice(1, 2); // 2 myArray = myArray.slice(1, 3); // 2,3 With two values it returns the numbers between the first number and the last number, not including the last number. The numbers are the same as array indexes (i.e. start at 0)
What is the splice method used for on an array?
It can be used to delete, insert and replace items in an array
Remove the first item form the following array using splice
colors = [“red”, “gree”, “blue”];
var removed = colors.splice(0, 1); // Remove the first item
Insert two items at position 1 using splice given the following array:
colors = [“red”, “gree”, “blue”];
var removed = colors.splice(1, 0, “yellow”, “orange”); // note, nothing is removed in this example
Insert two values, but delete one using splice from the following array
colors = [“red”, “yellow”, “green”];
var removed = colors.splice(1, 1, “red”, “purple”);
What functions can you use on an array to determine the lcoation of an item?
colors. indexOf(“red”);
colors. lastIndexOf(“red”);
What does the “every” iterator do on an array?
It is run on every element of an array, and returns true if the function returns true on every item.
What does the “some” iterator do on an array?
It is run on every element of the array and returns true if SOME of the elements of the array are evaluated as true.
What does the “filter” iterator do on an array?
It is run on every element and returns an array of elements that meet the criteria of the given function var numbers = [ 1, 2, 3, 4, 5, 6 ]; var filterResult = numbers.filter(function(item, index, array) { return item > 2; });
alert(filterResult); // [3, 4, 5, 6]
What does the “map” iterator do on an array?
It will run over every element in the array and perform an operation returning an array of the results var numbers = [ 1, 2, 4, 5]; var result = numbers.map(function(item, index, array) { return item * 2; }); alert(result); // [2, 4, 8, 10];
What does the forEach() iterator do on an array?
Runs over every element in the array, running the provided function. But note: there is no return value, it’s essentially equivalent to a for loop.
numbers.forEach(item, index, array) { // Do stuff here. });
What are the reduction methods in ECMAScript?
They are Array methods that iterate over an array, and apply a function to each element. The goal is to eventually accumulate all the values and provide a single result.
There are two - reduce and reduceRight();
var value = [1, 2, 3, 4, 5]; var sum = values.reduce(function(prev, cur, index, array) { return prev + cur; }
alert(sum); // 15
To convert a string representation of a date to milliseconds (since 1970), what function do you use?
Date.parse()
// Date format can either be // m/d/y (6/13/2014) // month_name date, year (January 12, 2004) // day_of_week month_name date year hours:minutes:seconds time_zone //YYYY-MM-DDTHH:mm:ss.sssZ
If you pass nonsense into Date.parse(), what does it return?
NaN
What is another way of using Date.parse() that reduces the amount of code required?
var someDate = new Date(“May 25, 2004”);
It calls Date.parse() in the constructor
If I wanted to get the exact date as of now - what function would I use?
Date.now()
In older versions of ECMAScript there is a difference between a regex literal and a RegExp object, what is it?
The regex literal only has one instance, so in a loop multiple calls to it would not create a new instance, and it search from the last place it left of. HOWEVER, a RegExp object would call it’s constructor each iteration, meaning the search was performed each iteration from the start of the string. New versions make the two consistent and Reg Ex literals now behave as though the constructor is called each time.
What is the main method used to perform a reg ex test on input when using the RegExp object?
RegExp.exec() var text = "mom dad"; var pattern = /mom/; var matches = pattern.exec(text); // NOTE matches will be an array of matches, if applicable
Write the following statement again, using assignment of the function: function sum(var1, var2) { return var1 + var2; }
var sum = function (var1, var 2) { return var1 + var2; }
Write the following function again, using a function constructor function sum(var1, var2) { return var1 + var2; }
var sum = new Function("var1", "var2", "return num1 + num2"); NOTE: This is not recommended way of doing things... It requires double interpretation, once for the object, and once for the strings that are passed in.
Why is function overloading not allowed in ECMAScript?
Because of the nature of functions in ECMAScript, they are basically pointers to a Function object, and that means redeclaring the same function overwrites the previous data. So it’s a side effect of functions being treated as objects.
What is function declaration hoisting?
The javascript engine parses the source and ‘hoists’ the declarations to the top of the source tree (so functions can be called BEFORE they are defined.
When does function declaration hoisting not help you?
When you have used a function expression var sum = function(num1, num2) { } The function must be called AFTER the delcaration of sum.
Is this code okay?
alert(sum(10, 10));
function sum(num1, num2) { }
Yes - function declaration hoisting makes sure the declaration is known before the code is executed
is this code okay?
alert (sum(10, 10));
var sum = function (num1, num2) {}
No - this will cause an error - as a function expression has been used, which is not subject to function declaration hoisting.
When you might you use a function as a return type?
Using the array / object sort function. It takes a single parameter (sort order function), you can use the function to the field to sort on as a parameter. The function then returns a function that does the sort (using the two appropriate objects to sort on).
function createCompFunction(propertyName) { return function(object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; if (value1 < value2) { return -1; } else if (value1 > value2) { return 1; } else { return 0; } }; }
What are the two special objects in a Javascript function?
arguments and this
How would you decouple a recursive function from it’s own name (in case the function name changes?)
// NOTE the arguments.callee method function factorial (num) { if (num <= 1) return 1; else return num * arguments.callee(num-1);
In Javascript, if you use this inside a function at the global level, to what does ‘this’ refer?
The window object (so values at a global scope)
What does the caller property do?
Accessed through the function (i.e. if your function is called inner, inner.caller). It references the function that called this function.
Rather than accessing the caller property through the function, how else can you get it to reduce coupling?
arguments.callee.caller
What is the value of arguments.callee.caller if called from the global scope?
null
Can arguments.callee be accessed in strict mode?
No
Why was arguments.callee removed in strict mode?
To prevent a security issue where 3rd party code running in the same context could inspect the code.
What does the length property contain on a function?
The number of named arguments that are expected
Is the prototype property enumerable?
No, so it can’t be found in a for-in clause
Where do the instance methods (such as toString and valueOf) live on a reference type?
On the prototype property
What does the following code do? function sum(num1, num2) { return num1 + num 2); } function callSum1(num1, num2) { return sum.apply(this, arguments); }
The use of the built in apply method (from the sum function), sets the ‘this’ value for inside the the sum function. It then passes in the arguments object for the callSum1 function.
In strict mode, if a function is called without a context object, is the ‘this’ value coercd to ‘window’?
No - instead this becomes undefined, unless explicitly set by either attaching the function to an object or using apply() or call()
What is the difference between the call and apply methods?
The way arguments are passed- apply will take an array or reference object, call takes each argument individually
Is the following equivalent? var value="25"; var number=Number(value); // casting alert(typeof number);
var obj = new Number (value); alert(typeof obj);
No - typeof obj will display “object”
typeof number will display “number”
So - using a casting function and calling a primitive wrapper function using “new” is not the same thing.
What is wrong with this code?
var str1 = “This is a string”;
str1.color = “red”;
alert(str1.color);
str1.color is undefined, as it is a simple type. A wrapper object is created when str1 is accessed in read mode, but it’s immediately destroyed. So there is no persistent object present for str1 in order to add a property.
What is wrong with this code?
var str1 = new String(“this is a string”);
str1.color = “red”;
alert(str1.color);
Nothing - because str1 is created as a basic type wrapper object, the object is persistent until it’s destroyed or out of scope. So adding a property is perfectly valid.
Calling typeof on an instance of a basic type wrapper object will return what?
Object
Is number a basic wrapper object, or a primitive type after this code? var value = "25"; var number = Number(value); alert(typeof number);
Primitive type. This is a casting operation and doesn’t use new. The casting functions have the same name as the Basic Wrapper object constructors.
Write a line of code to create a Boolean object (wrapper object):
var bool = new Boolean(true);
What is the problem with using Boolean objects in boolean expressions?
Boolean objects will evaluate to true, no matter what their actual value.
How would you remove any trailing and leading whitespace on a string?
var str = " this is a string with a lot of whitespace "; var trimmed = str.trim();
Given: var text = "cat, bat, sat, fat"; var pattern = /.at/; Write this following expression in another way: pattern.exec(text);
var matches = text.match(pattern);
The string method .replace can use a function as a second argument, how?
text.replace(/[<>"&]/g, function (match, pos, originalText) { switch($match) { case "": return "&rt;"; case "&": return "&"; case "\"": return """; } }); }
What are the two singleton built in objects in ECMAScript?
Math and Global
What is different about the Global object?
It’s not directly accessible. Any global vars / functions you create actually belong to this object.
What is the difference between encodeURI and encodeURIComponent?
encodeURI only encodes spaces, so it is suitable for passing a URL to it. encodeURIComponent encodes any and all non-alphanumeric characters, so it’s only suitable for use on strings which are going to be added to the end of a URI.
If I receive a string that has been encodeing using encodeURI and a part of the string also was encoded using encodeURIComponent, what do I do to return it to the original state?
var uri = "long url with encoding in it"; var url = decodeURIComponent(uri);
decodeURIComponent decodes all parts. You can also use decodeURI to change the %20’s back to spaces.
While Global is not accessible directly, what object acts as the Global objects delegate, allowing direct access to global variables?
window var color = "red"; alert(window.color); // Okay
What are the two types of properties that can be defined on an object?
Data property
Accessor property
What are the four attributes given to a data property in an object?
[[Configurable]] - can the property be redefined by removing the property via delete
[[Enumerable]] - Will the property be returned in a for-in loop?
[[Writable]] - Can the value be changed
[[Value]] - The actual data for the property
What are the default attributes given to a data property?
[[Configurable]] = true; [[Enumerable]] = true; [[Writable]] = true; [[Value]] = The value of the property
How would you create a person object with an attribute “name” that is not writable?
var person = { }; Object.defineProperty(person, "name", { writable: false; value: "Nicholas" });
What happens if you try to change a property that is defined as “writable: false”
In non-strict mode, it’s simply ignored. In strict mode, and error is thrown.
If you’ve set configurable on a property, can it be changed?
No - the only thing you can change on a data property once configurable is false is whether it is writable.
What are the Accessor properties?
[[Configurable]] // Can we remove the property using delete
[[Enumerable]] // Will the property be returned in a for-in loop?
[[Get]] - The function to call when property is read from (default undefined)
[[Set]] - The function to call when property is written to (default is undefined)
Is it possible to define an accessor property explicitly?
No - you must use the Object defineProperty() method.
Give an example of setting an accessor property for get and set:
var book = {
_year: 2004;
edition: 1;
}
Object.defineProperty(book, "year", { get: function() { return this._year; }, set: function(newValue) { if (newValue > 2004) { this._year = newValue; this.edition += newValue - 2004; } } });
If I assign a getter using defineProperty, what happens if I try to set the value?
Nothing - it will be ignored (strict mode, it will throw an error).
It’s common to have to define more than one property, what method can be used to do this?
Object.defineProperties()
How would you add a property called _year to an object using the defineProperty method?
var obj = {}; Object.defineProperty(book, { _year: { value: 2001 } });
How can you get information about an objects properties?
var descriptor= Object.getOwnPropertyDescriptor(obj, “var”);
alert(descriptor.value);
alert(descriptor.configurable) etc…
What pattern did developers start using to create objects in ECMAScript (to avoid code duplication)
Factory pattern
function CreatePerson(name) { var o = new Object(); o.name = name; o.sayName = function() {alert(this.name); }; return o; } // NOTE THIS has the issue that you cant determine what type of object it is, as it will always be 'Object'
What other method is more popular for creating objects?
function Person(name) { this.name = name; this.sayName = function() {alert(this.name)}; } var person1 = new Person("Steveo");
Objects in java have a property called ‘constructor’ - what can this be used for?
You can determine the type of an object like such:
personObj.constructor === Person; // True
But using instanceof is considered more safe
personObj instanceof Person; // True
If you create two objects from the same constructor, and each have the function myFunc, what does the following give?
obj1.myFunc == obj2.myFunc
False. Because each function is unique (i.e. recreated) for each object.
How can you get around the fact the constructor pattern creates a new version of any functions defined within the constructor?
Declare it outside the constructor function Person () { this.func = func; }
function func() { }
When a function is created, it receives a prototype member that has a constructor member - what does this point to?
It points back to the function that it belongs to (so a function called Person will have a prototype member with a constructor member that points to Person)
If I declare a prototype to have the following attribute…
Person.prototype.age
can I access it like this?
personObj.age?
Yes - even though it’s part of the prototype object, the lookup system finds age when referenced directly from the obj handle.
What function can we use to determine if a prototype is of a particular type?
Person.prototype.isPrototypeOf(person1);
What function can be used to get the prototype of an object?
Object.getPrototypeOf(person1)
NOTE: It’s a method on the Object object.
If a property is accessed for reading on an object, how is the search performed?
First it looks on the object instance. If found, the value is returned, else it looks at the objects pointer to it’s prototype - if found, the value is returned
If you create a property on an object with the same name as a property in it’s protoype, what happens?
The prototype version is masked. Note, you can’t overwrite the property, just ask it.
Why does the following code result in only one instance of the function in the object, rather than one per object? function Person() { this.sayName = sayName; }
function sayName() { }
Because this.sayName is a pointer to the function sayName, not an actual instance.
What property is created with each Javascript Function?
the prototype property
What is useful about the prototype property?
It is available to all variables of a particular reference type.
What is the only way to remove a property that is masking a property of the same name in a prototype?
Using delete keyword. Setting the property to null will do nothing.
What are the two ways the ‘in’ operator can be used?
In the for-in loop, and to test whether a variable is accessible within an object.
(i.e. “name” in person1; // True)
If a property is hidden by existing on both the prototype and the object, what will hasPrototypeProperty return?
false - because it will be picked up on the object first, and the prototype is not checked.
When creating an object using the ‘dynamic prototype’ method… what should you do?
You should test for the existence of the prototype, and only create it if it doesn’t exist already.
How would you test for the existence of a prototype when creating an object using the dynamic prototype pattern?
You would test for the existence of a method that should exist if the prototype exists. You only have to test for one method - any will do (and create all prototype functions within that block.
What is the parasitic constructor pattern?
An object is created and populated within a function. The object is assigned the values passed to the function, and then returned to the caller. function Person(name) { var o = new Object(); o.name = name; o.sayName = function() { alert(o.name); }; return o; }
var p = new Person(“Harrold”);
Why is the parasitic constructor pattern useful?
You can use it to extend functionality of existing (but not accessible) code. You wrap the function (say array), do whatever else you need to do with it, then return array.
What does the !! operator do?
Essentially a cast to Boolean. First bang coerced the value to the opposite of its Boolean value, the second bang reverts it back to its correct Boolean value. Note - doing this creates a primitive Boolean type - whereas casting using the Boolean() function creates a boxed type.
What does the ‘in’ operator do?
It takes a left hand operand (must be either string, or something that can convert to string). The right hand operand must be an object.
It returns true if the left hand operand exists in the object.
Using the typeof operator you can determine whether an object is of a certain type, what is another way?
// Where obj is of type Vector2 and Vector2 // is a class if (obj.constructor === Vector2) { }
What is a property in Javascript?
It is (similar to C# properties) - a way to implement setters and getters. It defines what happens when you try to get or set a value in the object.
Given an object called ‘cannon’ - implement a read-only property for a variable called ‘center’ that returns it’s position.
Object.defineProperty(Cannon.prototype, 'center', { get: function() { return new Vector2(this.currentColor.width / 2, this.currentColor.height / 2); } });
What is the name of the object that you use to create a property?
Object
What method on Object is used to create a property?
defineProperty
Is the ‘this’ member valid within an Object.defineProperty declaration?
Yes - ‘this’ will be available within the callback functions for ‘get:’ and ‘set:’. It refers to the object prototype passed as the first parameter to defineProperty.
How would you make a property on an object that returns a zero vector (assuming the vector object is called Vector2, and creating a new Vector2 object without arguments creates an empty vector).
object.defineProperty(Vector2, ‘zero’, {
get: function() {
return new Vector2();
}
});
What is another, shorter way of adding a property to an object?
Vector2['zero'] = function() { return new Vector2(); };
Methods that are defined using the defineProperty method (on an object) are like what in a class based language?
Static methods in that they are accessed through the class (function in javascript), and not through the instance.
Are set and get properties defined in the same code block?
Yes
object.defineProperty(Vector2, ‘zero’, {
get: function() {
return new Vector2();
},
set: function(v) {
this.x = v.x;
this.y = v.y;
}
});
What does a closure implementation look like?
var add = (function () { var counter = 0; return function () {return counter += 1;} })();
** NOTE: This is a self calling function. It calls itself once, setting counter to 0 and returning a reference to the anonymous function within. Then, when you call add(), the anonymous function that was returned increments the counter by one. This is called a closure - because it has access to the variable ‘counter’ in the parent scope - creating essentially, a private variable.
What has better performance, getter in closure form, or a getter implemented on the prototype?
A getter implemented on the prototype.
How do you implement inheritence in Javascript.
By copying the prototype of one object (the parent) into the child objects prototype. Assume there is a class called Vehicle. function Car() { Vehicle.call(this); // Calling the parent constructor } Car.prototype = Object.create(Vehicle.prototype);
What is the non-jquery way of calling javascript only when the entire page is loaded?
window.onload = function() { // Do stuff };
Does the script tag use the href or src attribute to point to the external file?
src
How do you override a method in Javascript.
Simply redefine the method on the prototype of the child / subclass.
Canon.prototype.draw = function() { }
When does a function invocation become a constructor invocation?
When it is preceded by the keyword new.
Is it possible to run an arbitrary function in the context of any object?
Yes, using the call, or apply functions, you can specify the object that will be used as the ‘this’ keyword in the function.
What would be the idiomatic way of writing the following expression?
if (a === undefined) a = [];
a = a || [];
// Because the || operator returns the first truthy argument
What is a good idea to do in the parameter list of a function if a parameter is optional?
Use a comment function foobar (a, /*optional*/b) { }
How would you use the arguments array to determine if the function is executed with the correct number of arguments?
function foobar(a, b, c) { if (arguments.length != 3) { throw new Error (stuff); } }
What is one very legitimate use for using the arguments array?
Writing functions that will take an unlimited number of parameters
function max(1, 4, 2, 67, 23, 234234, 4, 2, 34234, 234) { for (i = 0; i
Arguments array is not actually an array, but an object, what is one weird thing it can do in non-strict mode?
You can modify the value of the actual original parameters, by assigning a value to the appropriate element of the array.
// Don’t do this!
Can you use the parameter or local variable name ‘arguments’ in strict-mode?
No - in strict mode arguments acts like a keyword, and cannot be used.
What happens if you write too, or reference the callee and caller properties of the Arguments object in strict-mode?
It is guarenteed to throw a TypeError
What does the callee field of the Arguments object refer to?
The currently running function
What does the caller field of the Arguments object refer to?
It refers to the callstack - but note - this is a non-standard feature
What would be one use for the callee attribute on the Arguments object?
Recursive functions - allowing the function to call itself. This is particularly useful in un-named functions.
If you have a function that requires lots of parameters, what is one way to simplify the process of remembering each parameter name and order?
Pass an object instead that requires keyword:value pairs. The order of the parameters no longer matters
Is this legal, and if so how would you invoke the following function?
a = [function() { x * x; }, 10];
Yes it is legal.
a0;
Can a function be an element of an array?
Yes - functions are just data, and can be assigned to things just like data - such as variables and array elements.
How can you simulate a static variable in a JavaScript function?
Use a property (either as a property, or an array element on the function).
uniqueInteger.integer = 0; function uniqueInteger() { return uniqueInteger.integer++; }
How can you emulate a namespace in JavaScript?
Use a function, since variables have function scope.
function myModule() { // module code goes here. } myModule(); // Remember to invoke!!
// Idiomatic way of doing it using an IIFE
(function myModule() { // Module code goes here. }());
Which of the following is the correct way to invoke an IIFE?
(function() { // code goes here }());
(function() { // Code goes here })();
Both are correct.
What does lexical scoping mean?
It’s the method by which the javascript compiler determines the scope of variables - it uses the variable scope that was in effect when it was written, not when it is invoked.
What does this return?
var scope = "global scope"; // A global variable function checkscope() { var scope = "local scope"; // A local variable function f() { return scope; } // Return the value in scope here return f(); } checkscope()
“local scope”
What does this return? var scope = "global scope"; // A global variable function checkscope() { var scope = "local scope"; // A local variable function f() { return scope; } // Return the value in scope here return f; } checkscope()() // What does this return?
“local scope”
// Remember - lexical scoping says that the scope chain // that was in effect at the time of writing is used, not the // scope chain that is in-effect at time of calling!
note: checkscope()() - is invoking checkscope() then invoking the inner fucnction that is returned, f. It would be the same as
f = checkscope();
f();
What benefit does using a closure like below have?
var uniqueInteger = (function() { // Define and invoke var counter = 0; return function() { return counter++; }; }()); // IIFE
Because function() is a closure, it continues to have access to the counter variable. But that variable has become inaccessible to the outside world through any other means, effectively making it private.
Is it possible to create a closure where multiple functions can reference the same variable?
Yes.
function counter() { var n = 0; return { count: function() { return n++; }, reset: function() { n = 0; } }; }
var a = counter();
a. count();
a. reset();
Can the use of a shared variable and closure, be used with a accessors?
yes
function counter(n) { // Function argument n is the private variable return { get count() { return n++; }, set count(m) { if (m >= n) n = m; else throw Error("count can only be set to a larger value"); } }; }
a. count = 2000;
console. log(a.count); // 2000
// We use the parameter n here instead of the global variable so that we can specify the initial value on original invocation.
When checking the ‘length’ property of a function, what does it reference?
The ‘arity of the function - i.e. the number of parameters it expects.
In non-strict mode - how could you use the ‘length’ attribute to determine how many parameters should have been passed, from WITHIN the function?
arguments.callee.length
The call and apply function methods allow you to invoke an function as if it was…
a member of another object
What does the bind() function do?
It binds a method to an object.
// i.e. var myobject = { "foobar": 10 };
function myFunc(num) { console.log(this.foobar + " and another number: " + num); }
var x = myFunc.bind(myobject); x(21);