Javascript Built-In1
Javascript Built-In1
Prof.N.Nalini,
AP(Sr)
SCOPE
VIT
1
JavaScript Objects
Objects are collections of properties (equivalent to
members of classes in Java)
Properties are either data properties or method
properties
Data properties are either primitive values or
references to other objects
The Object object is the ancestor (through
prototype inheritance) of all objects in a JavaScript
program
Object has no data properties, but several method
properties
2
JavaScript Objects
JS has built-in objects
E.g. Math, Date, Array, String
Browser creates objects
These model the document (web page)
You can create your own objects
But JS has no class
Objects are built on-the-fly
3
Built-in Objects
There are objects corresponding to the 3
data primitives
Number, String, Boolean
(note the upper case first letter)
These wrap a single value and provide
some methods
One method all three wrapper objects have is
valueOf() - returns the corresponding primitive
value of an object
Create an object with new:
var doneObj = new Boolean(true);
var numObj = new Number(3.14159);
4
Built-in Objects
Boolean has no useful methods of its own
Number has formatting methods
toExponential(digitsAfterDP) - converts the value of the
object into an exponential notation with the # requested
digits after .
var num = new Number(10000);
document.write (num.toExponential(1));
writes into document 1.0e+4
toPrecision(numberOfDigits) - converts a number into a
number with the specified number of digits
toFixed(digitsAfterDP) - rounds the number to the
specified number of decimal places
5
Built-in Objects
String has many methods
Many are the same as for Java String object
indexOf, charAt, substring, etc.
Also has methods to create HTML strings
var st = new String(“I’m big and bold!”);
var st1 = st.bold();
var out = st1.big();
gives
<big><bold>I’m big and bold!</bold></big>
See
http://www.w3schools.com/jsref/jsref_obj_string.a
sp
for a complete reference
6
String
String
String
Object Conversions
JS does many automatic conversions
between primitives and objects
Previous example could be written:
var st = “I’m big and bold!”;
var out = st.big().bold();
In this case, the variable st is automatically
converted to a String object to make the first
method call and the resulting string is then
converted to a String object to call bold( )
10
Other Built-in Objects
Math
Like Java Math
No instance needed – all constants and methods
referenced through the Math object
Constants
○ Math.PI, Math.SQRT2, etc.
Methods
○ Trig functions: Math.sin( ), etc.
○ Number manipulation: Math.floor( ), Math.min( ),
Math.round()
○ Calculational: Math.pow( ), Math.exp( ), Math.random( ) -
like Java: [0, 1)
11
Math Object
Method Description Example
abs( x ) absolute value of x abs( 7.2 ) is 7.2
abs( 0.0 ) is 0.0
abs( -5.6 ) is 5.6
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
integer not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential method ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
integer not greater than x floor( -9.8 ) is -10.0
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
(base e) log( 7.389056 ) is 2.0
max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
Math Object
min( x, y ) smaller value of x min( 2.3, 12.7 ) is 2.3
and y min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y pow( 2.0, 7.0 ) is 128.0
(xy) pow( 9.0, .5 ) is 3.0
round( x ) rounds x to the round( 9.75 ) is 10
closest integer round( 9.25 ) is 9
sin( x ) trigonometric sine of sin( 0.0 ) is 0.0
x (x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent tan( 0.0 ) is 0.0
of x
(x in radians)
Fig. 12.1 Math object methods.
Math Object
Constant Description Value
Math.E Base of a natural Approximately 2.718.
logarithm (e).
Math.LN2 Natural logarithm of 2. Approximately 0.693.
Math.LN10 Natural logarithm of 10. Approximately 2.302.
Math.LOG2E Base 2 logarithm of e. Approximately 1.442.
Math.LOG10E Base 10 logarithm of e. Approximately 0.434.
Math.PI —the ratio of a circle’s Approximately
circumference to its 3.141592653589793.
diameter.
Math.SQRT1_2 Square root of 0.5. Approximately 0.707.
Math.SQRT2 Square root of 2.0. Approximately 1.414.
Fig. 12.2 Properties of the Math object.
Other Built-in Objects
Date
var dt = new Date( );
gives the current date
Date has getX and setX methods for X =
FullYear, Month, Day, Hours, Minutes,
Seconds and Milliseconds
Formatting methods return date as a string
toString( )
toGMTString( ) – converts to a string according
to Greenwich time.
toLocaleString( )
15
Arrays
JS has arrays which look like Java arrays
Standard variable names to reference Array objects
Indexed with [ ]
JS arrays are objects!
Can be created with new keyword
var newAr = new Array(“one”, “two”, “three”, 4);
var newAr = new Array(3);
1st way creates and initializes array (> 1 argument)
2nd way just sets size (1 int argument)
Can also be created with array literal
var newAr = [“one”, 2, “three”];
Note the square brackets, not braces
Note that values of different data types can be mixed
16
Arrays
Array elements are accessed as in Java: var first =
newAr[0];
Can be multi-dimensional as in Java
.length property gives the current length
= the highest subscript to which a value has been assigned + 1, or
the initial size, whichever is larger
Can be read or written
Arrays are not fixed in length
By setting new array elements using an index beyond the current
length, or by setting the length property to a larger value you extend
the array (very much NOT like Java)
By setting the length property to a smaller value you shrink the array
Space is not reserved for each element, only those defined
(assigned)
var a = new Array(5); // all are undefined
a[100] = 2; // has only 1 defined
17
Arrays
var list = [2, 4, 6, 8, 10]
slice() – returns part of an array: list.slice(1,3) => array [4, 6]
concat( ) – concatenates new elements to the end of the array;
returns new array: list.concat(12) => [2, 4, 6, 8, 10, 12]
join( ) – creates a string from the array elements, separated by
commas (or specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10”
reverse( ) – reverses order of the array elements; affects calling
array
sort( ) – converts elements to strings, sorts them alphabetically (or
you can specify another order as a function); affects calling array
push( ), pop( ) – add/delete elements to the high end of array
unshift( ), shift( ) – add/delete elements at the beginning of the
array
splice() - adds/removes items to/from an array, and returns the
removed item(s).
18
Associative Arrays
Array with non-numeric indices
Also called a hash
Created as Object and filled using index
value
var myHash = new Object();
myHash[“me”] = “Instructor”;
myHash[“you”] = “Student”;
for (var i in myHash)
alert (i + "-" + myHash[i]);
19
Functions
Several types of JS functions exist
We will focus on simple declarative functions
Like Java methods
Defined with keyword function
Parameters follow in parentheses
No parameter types required
() required even if no parameters are declared
Body of function in brackets (=compound statement)
Function terminates at end } or with return statement
No return type is declared
Function can return a value of any type or have no return value
20
Functions
Example:
function greet(hour, name) {
if(hour < 12)
document.write(“Good morning,
“+name);
else if(hour < 18)
document.write(“Good afternoon,
“+name);
else if(hour < 24)
document.write(“Good evening,
“+name);
else return false;
}
21
Functions
Note that the example function may or may not
return a value.
If no value is returned explicitly from function, the undefined
value is return by default
○ Could test by:
var result = greet(hour, name);
if(result != undefined) document.write(“Wrong hour”);
○ Note: no quotes on undefined
22
Functions
Functions used like Java methods
Calculations
Data checking
Any process you do more than once or want to
isolate
Note: a function definition should precede calls to
the function, to guarantee it is loaded before being
called → usually placed in head section
23
Functions
Formal parameters are local variables
All other local variables must be declared with var or else a
global variable may be used
Data types of arguments are not checked – just converted as
needed
24
Functions
JS uses pass-by-value parameter-
passing method
Primitives are passed by value
Changing the value in the function has no
effect at the calling site
Objects are passed by reference
Changing the object in the function
changes the caller’s object
25
Functions
Number of arguments passed to a function is not
checked against the number of formal parameters
in the called function
Excess actual parameters are ignored (however, see
below)
Excess formal parameters are set to undefined
○ i.e. if you define function f(a, b, c) and call it by f(p, q)
then c will be undefined when f executes
However, a property array named arguments holds all
of the actual params, whether or not there are more of
them than there are formal params:
for (var i=0; i<arguments.length; i++)
document.write(arguments[i] + “<br />”);
26
Anonymous Function
var x = function (a, b) {return a * b};
var z = x(4, 3);
The function above is actually an
anonymous function (a function
without a name).
Functions stored in variables do not
need function names. They are always
invoked (called) using the variable
name.
27
Self-Invoking Functions
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started)
automatically, without being called.
Function expressions will execute automatically if
the expression is followed by ().
You cannot self-invoke a function declaration.
You have to add parentheses around the function
to indicate that it is a function expression:
28
Self-Invoking Functions
Example
(function () {
var x = "Hello!!"; // I will invoke myself
})();
It is called anonymous self-invoking
function (function without name).
29
User-defined Objects, Creation&Modification
The new expression is used to create an object:
This includes a call to a constructor method
The new operator creates a blank (empty) object, the constructor
creates and initializes all properties of the object
Properties of an object (data and methods) are
accessed using a dot notation: object.property; or
the object[property] notation.
30
User-defined Objects, Creation
&Modification
Properties are not variables, they are
just the names of values, so they are not
declared
An object may be thought of as a
Map/Dictionary/Associative-Storage
The number of properties of an object
may vary dynamically in JS; properties
can be added/deleted from an object at
any time during interpretation
31
User-defined Objects, Dynamic Properties
Create my_car and add some properties
// Create an Object object with no properties
var my_car = new Object();
// Create and initialize the make property
my_car.make = "Ford";
// Create and initialize the model property
my_car.model = "Contour SVT";
32
The for-in Loop
Syntax: for (identifier in object)
statement or compound statement
The loop lets the identifier take on each property
(name) in turn in the object
Printing the properties in my_car:
for (var prop in my_car)
document.write("Name: " + prop + "; Value: " +
my_car[prop] + "<br />");
Result:
Name: make; Value: Ford
Name: model; Value: Contour SVT
33
Functions are Objects
Functions are objects in JavaScript
Functions may, therefore, be assigned to variables and to object
properties
Object properties that have function values are methods of the object
Example:
function fun() {
document.write("This surely is fun! <br/>");
}
ref_fun = fun; // Now, ref_fun refers to the fun object
fun(); // A call to fun
ref_fun(); // Also a call to fun
34
Constructors
Constructors are functions that create and
initialize properties for new objects; have same
name as object being created
A constructor uses the keyword this in the
body to reference the object being initialized
35
Constructors
Object methods are properties that refer
to / point to functions
A function to be used as a method may use
the keyword this to refer to the object for
which it is acting
36
Object Constructor
function Person(fname, lname) {
// Define and initialize fields
this.firstName = fname;
this.lastName = lname;
// Define a method
this.sayHi = function() {
alert("Hi! " + this.firstName + " " +
this.lastName);
}
}