71
Javascript - Reference Types @farhan-faruque

Javascript - Reference types

Embed Size (px)

Citation preview

What?A reference value (object) is an instance of a specific reference type.Reference types are also sometimes called object definitions,because they describe the properties and methods that objects should have.New objects are created by using the new operator followed by a constructor. var person = new Object();

THE OBJECT TYPEThe Object type, which is one of the most often-used types in ECMAScript.Object don’t have much functionality, they are ideally suited to storing and transmitting data around an application.There are two ways to explicitly create an instance of Object.➔ use the new operator with the Object constructor

var person = new Object();

➔ use object literal notation.var person = {

name : “Nicholas”,age : 29};

THE OBJECT TYPEIt’s also possible to create an object using object literal notation.

var person = {};person.name = “Nicholas”;person.age = 29;

Although object properties are typically accessed using dot notation, it’s also possible to access properties via bracket notation.

alert(person[“name”]);//”Nicholas”alert(person.name);//”Nicholas”

The main advantage of bracket notation is that it allows you to use variables for property access

var propertyName = “name”;alert(person[propertyName]); //”Nicholas”

THE ARRAY TYPEECMAScript arrays are ordered lists of data, but unlike in other languages, they can hold any type of data in each slot.ECMAScript arrays are also dynamically sized, automatically growing to accommodate any data that is added to them.Arrays can be created in two basic ways:➔ use the Array constructorvar colors = new Array()var colors = Array(3); //create an array with three itemsvar names = Array(“Greg”); //create an array with one item, the string “Greg”

➔ create an array is by using array literal notationvar colors = [“red”, “blue”, “green”]; //creates an array with three stringsvar names = []; //creates an empty array

Array length A unique characteristic of length is that it’s not read-only. By setting the length property, we can easily remove items from or add items to the end of the array.

var colors = [“red”, “blue”, “green”]; //creates an array with three stringscolors.length = 2;alert(colors[2]); //undefined

If the length were set to a number greater than the number of items in the array, the new items would each get filled with the value of undefined.

var colors = [“red”, “blue”, “green”];colors.length = 4;alert(colors[3]); //undefined

Detecting Arrays ECMAScript 5 introduced the Array.isArray() method.

if (Array.isArray(value)){//do something on the array}

Conversion Methodsvar colors = [“red”, “blue”, “green”];//creates an array with three stringsalert(colors.toString());//red,blue,greenalert(colors.valueOf());//red,blue,greenalert(colors);//red,blue,green

join() - construct a string with a different separator - accepts one argument, which is the string separator to use- returns a string containing all items

var colors = [“red”, “green”, “blue”];alert(colors.join(“,”));//red,green,bluealert(colors.join(“||”));//red||green||blue

push() - adds items to the end of an array.pop() - removes the last item in the array, decrements the array’s length, and returns that item.

var colors = new Array(); //create an arrayvar count = colors.push(“red”, “green”); //push two itemsalert(count); //2

count = colors.push(“black”); //push another item onalert(count); //3

var item = colors.pop(); alert(item); //”black” alert(colors.length); //2

Stack Methods

Queue Methodsshift() - removes the first item in the array and returns itunshift() - adds any number of items to the front of an array and returns the new array length

var colors = new Array(); //create an arrayvar count = colors.push(“red”, “green”); //push two itemsalert(count); //2 var item = colors.shift(); //get the first itemalert(item); //”red”var count = colors.unshift(“blue”, “yellow”); //push two itemsalert(colors); //[ “blue”, “yellow”, “green” ]

Reordering Methods➔ reverse()

var values = [1, 2, 3, 4, 5];values.reverse();alert(values); //5,4,3,2,1

➔ sort()var values = [0, 1, 5, 10, 15];values.sort();alert(values); //0,1,10,15,5the sort() method calls the String() casting function on every item and then compares the strings to determine the correct order.

Comparison functionsort() - allows us to pass in a comparison function that indicates which value should come before which.

function compare(value1, value2) {

if (value1 < value2) {

return -1;

} else if (value1 > value2) {

return 1;

} else {

return 0;

}

}

var values = [0, 1, 5, 10,15];values.sort(compare);alert(values); //0,1,5,10,15

Manipulation Methodsconcat() - allows to create a new array based on all of the items in the current array

var colors = [“red”, “green”, “blue”];var colors2 = colors.concat(“yellow”, [“black”, “brown”]);alert(colors););//red,green,bluealert(colors2//red,green,blue,yellow,black,brown

- When no arguments are passed in, concat()simply clones the array and returns it.

- If the values are not arrays, they are simply appended to the end of the resulting array

Manipulation Methodsslice() - creates an array that contains one or more items already contained in an array.

- may accept one or two arguments: the starting and stopping positions of the items to return.

var colors = [“red”, “green”, “blue”, “yellow”, “purple”];var colors2 = colors.slice(1);var colors3 = colors.slice(1,4);alert(colors2); //green,blue,yellow,purplealert(colors3); //green,blue,yellow

If only one argument is present, the method returns all items between that position and the end of the array.

splice() methodsplice() - insert items into the middle of an array.there are three distinct ways of using this method:

Deletion — Any number of items can be deleted from the array by specifying just two arguments: the position of the first item to delete and the number of items to delete.

var colors = [“red”, “green”, “blue”];var removed = colors.splice(0,1); //remove the first itemalert(colors);//green,bluealert(removed);//red - one item array

splice() methodInsertion — Items can be inserted into a specific position by providing three or more arguments: the starting position, 0 (the number of items to delete), and the item to insert. Optionally, you can specify a fourth parameter, fifth parameter, or any number of other parameters to insert.

var colors = [“green”, “blue”];removed = colors.splice(1, 0, “yellow”, “orange”); //insert two items at position 1alert(colors);//green,yellow,orange,bluealert(removed); //empty array

splice() methodReplacement - Items can be inserted into a specific position while simultaneously deleting items, if you specify three arguments: the starting position, the number of items to delete, and any number of items to insert. The number of items to insert doesn’t have to match the number of items to delete

var colors = [“green”, “yellow”,”orange”,“blue”];removed = colors.splice(1, 1, “red”, “purple”);//insert two values, remove onealert(colors);//green,red,purple,orange,bluealert(removed);//yellow - one item array

Location MethodsindexOf() - starts searching from the front of the array (item 0) and continues to the backvar numbers = [1,2,3,4,5,4,3,2,1];alert(numbers.indexOf(4)); //3alert(numbers.indexOf(4, 4));//5

lastIndexOf() - starts from the last item in the array and continues to the front.alert(numbers.lastIndexOf(4)); //5alert(numbers.lastIndexOf(4, 4)); //3each accepts two arguments: the item to look for and an optional index from which to start looking.

each return the position of the item in the array or –1 if the item isn’t in the array.

Iterative Methodsevery() - Runs the given function on every item in the array and returns true if the function returns true for every item.

var numbers = [1,2,3,4,5,4,3,2,1];var everyResult = numbers.every(function(item, index, array){

return (item > 2);});alert(everyResult); //false

Iterative Methodsfilter() — Runs the given function on every item in the array and returns an array of all items for which the function returns true.

var numbers = [1,2,3,4,5,4,3,2,1];var filterResult = numbers.filter(function(item, index, array){

return (item > 2);});alert(filterResult);//[3,4,5,4,3]

Iterative MethodsforEach() - Runs the given function on every item in the array. This method has no return value.

var numbers = [1,2,3,4,5,4,3,2,1];numbers.forEach(function(item, index, array){//do something here});

Iterative Methodsmap() — Runs the given function on every item in the array and returns the result of each function call in an array.

var numbers = [1,2,3,4,5,4,3,2,1];var mapResult = numbers.map(function(item, index, array){

return item * 2;});alert(mapResult); //[2,4,6,8,10,8,6,4,2]

Iterative Methodssome() — Runs the given function on every item in the array and returns true if the function returns true for any one item.

var numbers = [1,2,3,4,5,4,3,2,1];var someResult = numbers.some(function(item, index, array){

return (item > 2);});alert(someResult); //true

Reduction MethodsMethods iterate over all items in the array and build up a value that is ultimately returned.methods accept two arguments: a function to call on each item and an optional initial value upon which the reduction is based.

reduce() - starting at the first item and traveling toward the lastvar values = [1,2,3,4,5];var sum = values.reduce(function(prev, cur, index, array){

return prev + cur;});alert(sum); //15

Reduction MethodsreduceRight() - starts at the last and travels toward the first.

var values = [1,2,3,4,5];var sum = values.reduceRight(function(prev, cur, index, array){return prev + cur;});alert(sum); //15

THE DATE TYPEThe Date type stores dates as the number of milliseconds that have passed since midnight on January 1, 1970 UTC (Universal Time Code)var now = new Date();When the Date constructor is used without any arguments, the created object is assigned the current date and time.

Date.parse()ECMAScript provides two methods: Date.parse() and Date.UTC().Date.parse() support - ● month/date/year (such as 6/13/2004)● month_name date, year (such as January 12, 2004)● day_of_week month_name date year hours:minutes:seconds time_zone

(such as Tue May 252004 00:00:00 GMT-0700)● ISO 8601 extended format YYYY-MM-DDTHH:mm:ss.sssZ (such as 2004-

05-25T00:00:00). This works only in ECMAScript 5–compliant implementations.

Date.parse()var someDate = new Date(Date.parse(“May 25, 2004”));

If the string passed into Date.parse() doesn’t represent a date, then it returns NaN.var someDate = new Date(“May 25, 2004”);

The Date constructor will call Date.parse() behind the scenes if a string is passed in directly.

Date.UTC() The Date.UTC() method also returns the millisecond representation of a date but constructs that value using different information than Date.parse().The arguments for Date.UTC() - zero-based

//January 1, 2000 at midnight GMTvar y2k = new Date(Date.UTC(2000, 0));//May 5, 2005 at 5:55:55 PM GMTvar allFives = new Date(Date.UTC(2005, 4, 5, 17, 55, 55));

Of these arguments, only the first two (year and month) are required

Date.UTC() As with Date.parse(), Date.UTC() is mimicked by the Date constructor but with one major difference: the date and time created are in the local time zone, not in GMT.

//January 1, 2000 at midnight in local timevar y2k = new Date(2000, 0);//May 5, 2005 at 5:55:55 PM local timevar allFives = new Date(2005, 4, 5, 17, 55, 55);

ECMAScript 5 adds Date.now() - returns the millisecond representation of the date and time

var start = Date.now()

Date-Formatting Methods● toDateString() ● toTimeString()● toLocaleDateString()● toLocaleTimeString()● toUTCString()

THE REGEXP TYPEvar expression = /pattern/flags;

Pattern - any simple or complicated regular expression including character classes, quantifiers, grouping, lookaheads, and backreferences.Three supported flags represent matching modes : ➢ g - global mode, meaning the pattern will be applied to all of the string

instead of stopping after the first match is found.➢ i — case-insensitive mode, meaning the case of the pattern and the

string are ignored when determining matches.➢ m — multiline mode, meaning the pattern will continue looking for

matches after reaching the end of one line of text.

THE REGEXP TYPE//Match all instances of “at” in a string.

var pattern1 = /at/g;

//Match the first instance of “bat” or “cat”, regardless of case.var pattern2 = /[bc]at/i;

//Match all three-character combinations ending with ”at”, regardless of case.

var pattern3 = /.at/gi;

THE FUNCTION TYPEFunctions actually are objects.Each function is an instance of the Function type that has properties and methods just like any other reference type.Function names are simply pointers to function objects and are not necessarily tied to the function itself

var sum = function(num1, num2){return num1 + num2;

};

a variable sum is defined and initialized to be a function.

Function constructorFunction constructor accepts any number of arguments.The last argument is always considered to be the function body, and the previous arguments enumerate the new function’s arguments.//not recommendedvar sum = new Function(“num1”, “num2”, “return num1 + num2”);

Because function names are simply pointers to functions, they act like any other variable containing a pointer to an object.

Function Declarations vs Function Expressions

a JavaScript engine loads data into the execution context. Function declarations are read and available in an execution context before any code is executed,whereas function expressions aren’t complete until the execution reaches that line of code.

alert(sum(10,10));function sum(num1, num2){

return num1 + num2;}#This code runs perfectly

alert(sum(10,10));var sum = function(num1, num2){return num1 + num2;};

#This updated code will cause an error

Functions as ValuesFunctions can be used any place any other value can be used. function callSomeFunction(someFunction, someArgument){

return someFunction(someArgument);}function add10(num){

return num + 10;}var result1 = callSomeFunction(add10, 10);alert(result1); //20

The callSomeFunction() function is generic, so it doesn’t matter what function is passed in as the first argument — the result will always be returned from the first argument being executed.

Function InternalsTwo special objects exist inside a function: arguments and this. The arguments object - is an array-like object that contains all of the arguments that were passed into the function. the arguments object also has a property named callee, which is a pointer to the function that owns the arguments object.

function factorial(num){ if (num <= 1) { return 1; } else { return num * arguments.callee(num-1) }}

Function Internalsthis - a reference to the context object that the function is operating on.

window.color = “red”;var o = { color: “blue” };

function sayColor(){ alert(this.color);}

sayColor();//”red”

o.sayColor = sayColor;o.sayColor();//”blue”

Function Properties and Methods

Each function has two properties: length and prototype.The length property - indicates the number of named arguments that the function expects.

function sayName(name){ alert(name);}

function sum(num1, num2){ return num1 + num2;}alert(sayName.length); //1alert(sum.length); //2

Function Properties and Methods

The prototype is the actual location of all instance methods for reference types.Methods such as toString() and valueOf() actually exist on the prototype and are then accessed from the object instances.

apply() and call()apply() and call() - both call the function with a specific this value, effectively setting the value of the this object inside the function body.The apply()method accepts two arguments: the value of this inside the function and an array of arguments.

function sum(num1, num2){return num1 + num2;

}function callSum1(num1, num2){

return sum.apply(this, arguments);}alert(callSum1(10,10));//20

apply() and call()The call() method exhibits the same behavior as apply(), but arguments are passed to it differently. The first argument is the this value, but the remaining arguments are passed directly into the function.

function sum(num1, num2){ return num1 + num2;}function callSum(num1, num2){ return sum.call(this, num1, num2);}alert(callSum(10,10));//20

apply() and call()The true power of apply() and call() - ability to augment the this value inside of the function.

window.color = “red”;var o = { color: “blue” };

function sayColor(){ alert(this.color);}

sayColor();//redsayColor.call(this);//redsayColor.call(window); //redsayColor.call(o);//blue

bind()The bind() method creates a new function instance whose this value is bound to the value that was passed into bind().

window.color = “red”;var o = { color: “blue” };function sayColor(){alert(this.color);}var objectSayColor = sayColor.

PRIMITIVE WRAPPER TYPESThree special reference types are designed to ease interaction with primitive values: the Boolean type, the Number type, and the String type.

Every time a primitive value is read, an object of the corresponding primitive wrapper type is created behind the scenes, allowing access to any number of methods for manipulating the data.

var s1 = “some text”;var s2 = s1.substring(2);

PRIMITIVE WRAPPER TYPESBehind the scene when a string value is accessed in read mode -

- Create an instance of the String type.- Call the specified method on the instance.- Destroy the instance.

PRIMITIVE WRAPPER TYPESThe major difference between reference types and primitive wrapper types is the lifetime of the object.

When we instantiate a reference type using the new operator, it stays in memory until it goes out of scope,

whereas automatically created primitive wrapper objects exist for only one line of code before they are destroyed.

PRIMITIVE WRAPPER TYPESvar s1 = “some text”;s1.color = “red”;alert(s1.color); //undefined

This happens because the String object that was created in the second line is destroyed by the time the third line is executed.

The Boolean Typevar booleanObject = new Boolean(true);

Instances of Boolean override the valueOf() method to return a primitive value of either true or false.

The Number TypeThe Number type is the reference type for numeric values.var numberObject = new Number(10);

the Number type overrides valueOf(), toLocaleString(), and toString(). var num = 10;alert(num.toFixed(2)); //”10.00”

toFixed() method returns a string representation of a number with a specified number of decimal pointsalert(num.toExponential(1)); //”1.0e+1”alert(num.toPrecision(1)); //”1e+2”alert(num.toPrecision(2)); //”99”alert(num.toPrecision(3));//”99.0”

The String Typevar stringObject = new String(“hello world”);

All three of the inherited methods — valueOf(), toLocaleString(), and toString() — return the object’s primitive string value.

var stringValue = “hello world”;alert(stringValue.length); //”11”

Character MethodsTwo methods access specific characters in the string: charAt() and charCodeAt().These methods each accept a single argument, which is the character’s zero-based position.var stringValue = “hello world”;alert(stringValue.charAt(1)); //”e”alert(stringValue.charCodeAt(1)); //outputs “101”

ECMAScript 5 defines bracket notation with a numeric index to access a specific character in the stringalert(stringValue[1]); //”e”

String Manipulation Methodsconcat() - which is used to concatenate one or more strings to another, returning the concatenated string as the result.

var stringValue = “hello “;var result = stringValue.concat(“world”);var result1 = stringValue.concat(“world”, “!”);alert(result); //”hello world”alert(result1); //”hello world!”

String Manipulation Methodsslice() - return a substring of the string they act on,and accept either one or two arguments. The first argument is the position where capture of the substring begins.The second argument is the position before which capture is stopped. If the second argument is omitted in any case, it is assumed that the ending position is the length of the string.A negative argument is treated as the length of the string plus the negative argument.

String Manipulation Methodsvar stringValue = “hello world”;alert(stringValue.slice(3)); //”lo world”alert(stringValue.slice(3, 7)); //”lo w”alert(stringValue.slice(-3)); //”rld”alert(stringValue.slice(3, -4)); //”hel”

String Manipulation Methodssubstr() - same as slide() but the second argument is the number of characters to return. a negative first argument is treated as the length of the string plus the number, whereas a negative second number is converted to 0.var stringValue = “hello world”;alert(stringValue.substr(3)); //”lo world”alert(stringValue.substr(3, 7)); //”lo worl”alert(stringValue.substr(-3)); //”rld”alert(stringValue.substr(3, -4)); // “” empty string

String Manipulation Methodssubstring() - same as slice() but all negative numbers are converted to 0.

var stringValue = “hello world”; alert(stringValue.substring(3)); //”lo world”alert(stringValue.substring(3,7)); //”lo w”alert(stringValue.substring(-3)); //”hello world”alert(stringValue.substring(3, -4)); //”hel”

substring(3, -4) - equivalent to substring(3, 0), which is actually equivalent to substring(0,3), because this method expects that the smaller number is the starting position and the larger one is the ending position.

String Location MethodsThere are two methods for locating substrings within another string: indexOf() and lastIndexOf().The difference between the two is that

- the indexOf() - begins looking for the substring at the beginning of the string

- the lastIndexOf() - begins looking from the end of the string.var stringValue = “hello world”;alert(stringValue.indexOf(“o”)); //4alert(stringValue.lastIndexOf(“o”));//7

indexOf() and lastIndexOf()Each method accepts an optional second argument that indicates the position to start searching from within the string.

var stringValue = “hello world”;alert(stringValue.indexOf(“o”, 6));//7alert(stringValue.lastIndexOf(“o”, 6));//4

The trim() Methodtrim() - creates a copy of the string, removes all leading and trailing white space, and then returns the result.

var stringValue = “ hello world “;var trimmedStringValue = stringValue.trim();alert(stringValue);//” hello world ”alert(trimmedStringValue); //”hello world”

String Case Methods

var stringValue = “hello world”; alert(stringValue.toLocaleUpperCase());//”HELLO WORLD”alert(stringValue.toUpperCase());//”HELLO WORLD”alert(stringValue.toLocaleLowerCase());//”hello world”alert(stringValue.toLowerCase()); //”hello world”

The Global ObjectThe Global object is the most unique in ECMAScript, because it isn’t explicitly accessible.In truth, there is no such thing as a global variable or global function; all variables and functions defined globally become properties of the Global object.

URI-Encoding Methodsa URI cannot contain certain characters, such as spaces.The URI-encoding methods encode the URIs so that a browser can still accept and understand them, replacing all invalid characters with a special UTF-8 encoding.encodeURI() - designed to work on an entire URIencodeURIComponent()- designed to work solely on a segment of a URI

URI-Encoding Methodsvar uri = “http://www.wrox.com/illegal value.htm#start”;//”http://www.wrox.com/illegal%20value.htm#start”alert(encodeURI(uri));//”http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start”alert(encodeURIComponent(uri));

Here , encodeURI()- left the value completely intact except for the space encodeURIComponent() - replaced all nonalphanumeric characters with their encoded equivalents.

The eval() MethodThis method works like an entire ECMAScript interpreter and accepts one argument, a string of ECMAScript (or JavaScript) to execute.eval(“alert(‘hi’)”);

This line is functionally equivalent: alert(“hi”);

When the interpreter finds an eval() call, it interprets the argument into actual ECMAScript statements and then inserts it into place.

The Window ObjectECMA-262 doesn’t indicate a way to access the Global object directly,web browsers implement it such that the window is the Global object’s delegate.

var color = “red”;function sayColor(){alert(window.color);}window.sayColor(); //”red”

Here, a global variable named color and a global function named sayColor() are defined.

The Math ObjectThe min() and max() Methodsvar max = Math.max(3, 54, 32, 16);alert(max);//54var min = Math.min(3, 54, 32, 16);alert(min); //3

Rounding Methodsalert(Math.ceil(25.9)); //26alert(Math.round(25.9)); //26alert(Math.round(25.5)); //26alert(Math.round(25.1)); //25alert(Math.floor(25.9)); //25

The random() MethodThe Math.random() method returns a random number between the 0 and the 1, not including either 0 or 1.Math.random() to select numbers within a certain integer range:number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)

a number between 1 and 10:var num = Math.floor(Math.random() * 10 + 1);

Other Methods

METHOD DESCRIPTION

Math.abs(num) Returns the absolute value of (num )

Math.exp(num) Returns Math.E raised to the power of (num )

Math.log(num) Returns the natural logarithm of (num )

Math.pow(num, power) Returns num raised to the power of power

Math.sqrt(num) Returns the square root of (num )

Math.acos(x) Returns the arc cosine of x

Math.asin(x) Returns the arc sine of x

Reference