javascript objects

Post on 07-Jul-2015

127 views 2 download

Tags:

description

javascript objects

Transcript of javascript objects

Java Script Objects

Objects

● An object is an unordered collection of properties, each of which has a name and a value.

● Property names are strings, so objects map strings to values.

● In addition to maintaining its own set of properties, a JavaScript object also inherits the properties of its “prototype” object.

● JavaScript objects are dynamic—properties can usually be added and deleted

● Objects are mutable and are manipulated by reference rather than by value.

Creating Objects

● Objects can be created with object literals, with the new keyword, and (in ECMAScript 5) with the Object.create() function.

● An object literal is a comma-separated list of colon-separated properties (name:value pairs), enclosed within curly braces

● A property name is a JavaScript identifier or a string literal (the empty string is allowed).

● A property value is any JavaScript expression; the value of the expression (it may be a primitive value or an object value) becomes the value of the property.

Creating Objects

● Examples● var empty = {}; // An object with no properties● var point = { x:0, y:0 }; // Two properties● // With more complex properties

var point2 = { x:point.x, y:point.y+1 };● // Nonidentifier property names are quoted

var book = { "main title": "JavaScript", // space in property nam

'sub-title': "Pocket Ref", // punctuation in name

"for": "all audiences", // reserved word name

};

Creating Objects with new

● The new operator creates and initializes a new object.

● The new keyword must be followed by a function invocation (such functions is called a constructor and serves to initialize a newly created object).

● Core JavaScript includes built-in constructors for native types, own constructor functions can be defined to initialize newly created objects.

Creating Objects with new

● Examples– var o = new Object(); // An empty object: same as

{}.

– var a = new Array(); // An empty array: same as [].

– var d = new Date (); //A Date for the current time.

– var r = new RegExp("js"); // A pattern matching object.

Prototype Object

● Every Java-Script object has a second JavaScript object (or null, rarely) associated with it, called as Prototype, from which the properties are inherited

● All objects created by object literals have the same prototype object refered in code : Object.prototype

● Objects created using the new keyword and a constructor invocation use the value of the prototype property of the constructor function as their prototype.

Prototype Object

● Object created by new Object() inherits from Object.prototype just as the object created by {} does.

● The object created by new Array() uses Array.prototype as its prototype, and the object created by new Date() uses Date.prototype as its prototype.

● Object.prototype is one of the rare objects that has no prototype: it does not inherit any properties.

● All other prototype objects inherit from Object.prototype object, so the objects created using other objects like Date(), Array() etc inherit from both the corresponding prototype object and Object.prototype (prototype chain).

Creating Objects using Object.create()

● Object.create(), creates a new object, using its first argument as the prototype of that object.

● Object.create() also takes an optional second argument that describes the properties of the new object.

● Object.create() is a static function, not a method invoked on individual objects.

Creating Objects using Object.create()

● Example– // o1 inherits properties x and y.

var o1 = Object.create({x:1, y:2});

– // o2 inherits no properties or methods, no basic methods will works as nothing is inherited

var o2 = Object.create(null);

– // o3 is like {} or new Object().

var o3 = Object.create(Object.prototype);

Objects

● Objects have attributes and methods.● Many pre-defined objects and object types

exist.● Using objects follows the syntax of C++/Java:

– objectname.attributename

– objectname.methodname()

The document object

● Many attributes of the current document are available via the document object:– Title

– Referrer

– URL

– Images

– Forms

– Links

– Colors

document Methods

● document.write() – the output goes into the HTML document.– document.write("My title is" + document.title);

● document.writeln() - adds a newline after printing.

The navigator Object

● Represents the browser and is a Read-only ● Attributes include:

– appName

– appVersion

– platform

navigator Example

if (navigator.appName == "Microsoft Internet Explorer") {

document.writeln("<H1>This page requires Netscape!</H1>");

}

The window Object

● Represents the current window.● There are possible many objects of type

Window, the predefined object window represents the current window.

● Access to, and control of, a number of properties including position and size.

window attributes and methods

● Attributes– document

– name

– Status ( the status line)

– Parent

● Methods– Alert() – Close()– Prompt()– MoveTo()– MoveBy() – Open()– scroll()– ScrollTo()– resizeBy()– resizeTo()

String Object● A string is an immutable ordered sequence of 16-bit

values, each of which represents a Unicode character - strings are JavaScript’s type for representing text.

● JavaScript does not have a special type that represents a single character of a string – To represent a single 16-bit value, we need to use a string that has a length of 1.

● Double-quote characters may be contained within strings delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes

String Object

● "" // The empty string: it has zero characters; ● ' name="myform" '● "Wouldn't you prefer O'Reilly's book?"● "This string\nhas two lines"● "π = 3.14"

Escape Sequences

● Backslash (\) is used to represent escape sequences

● \xYY - The Latin-1 character rep by two hexadecimal digits XX

● \uXXXX - The Unicode character specified by the four hexadecimal digits XXXX

JavaScript escape sequences

● Sequence Character represented● \0 The NUL character (\u0000)● \b Backspace (\u0008)● \t Horizontal tab (\u0009)● \n Newline (\u000A)● \v Vertical tab (\u000B)● \f Form feed (\u000C)● \r Carriage return (\u000D)● \" Double quote (\u0022)● \' Apostrophe or single quote (\u0027)● \\ Backslash (\u005C)

String Concatenation & String Length

● String Concatenation is supported by + operator

● msg = "Hello, " + "world"; // => "Hello, world"● To determine the length of a string, the

number of 16-bit values it contains, is retrieved using the length property of the string - s.length

String Methods

● var s = "hello, world"● s.charAt(0)● s.charAt(s.length-1)● s.substring(1,4)● s.slice(1,4)● s.slice(-3)● s.indexOf("l")● s.lastIndexOf("l")● s.indexOf("l", 3)● s.split(", ")● s.replace("h", "H")● s.toUpperCase()

● //Start with some text as example● => "h": the first character.● => "d": the last character.● => "ell": chars 2, 3, and 4● => "ell": same thing● => "rld": last 3 characters● => 2: position of first l.● => 10: position of last l.● => 3: position at or after 3● => ["hello", "world"]● => "Hello, world":● replaces all instances● => "HELLO, WORLD"

Immutable Property of Strings

● Strings are immutable in JavaScript. ● Methods like replace() and toUpperCase() return new strings: they

do not modify the string on which they are invoked.● In ECMAScript 5, strings can be treated like read-only arrays, and

we can access individual characters (16-bit values) from a string using square brackets instead of the charAt() method:

● s = "hello, world";● s[0] // => "h"● s[s.length-1] // => "d"

String to Numbers Conversion

● Global Functions– parseInt()

● parses only integers● If a string begins with “0x” or “0X,” parseInt() interprets it as a hexadecimal

number.● It accepts an optional second argument specifying the radix (base) of the

number to be parsed. (2 to 36)

– parseFloat() - parses both integers and floating-point numbers.

– Both functions skip leading whitespace, parse as many numeric characters as they can, and ignore anything that follows.

– If the first nonspace character is not part of a valid numeric literal, they return NaN

String to Numbers Conversion

● Examples– parseInt("3 blind mice") // => 3

– parseFloat(" 3.14 meters") // => 3.14

– parseInt("-12.34") // => -12

– parseInt("0xFF") // => 255

– parseFloat("$72.47"); // => NaN

– parseInt("11", 2); // => 3 (1*2 + 1)

– parseInt("077", 8); // => 63 (7*8 + 7)

– parseInt("ff", 16); // => 255 (15*16 + 15)

Number Conversion to String

● var n = 123456.789;● n.toFixed(2); // "123456.79"● n.toExponential(3); // "1.235e+5"● n.toPrecision(7); // "123456.8"

toString()

● The toString() method defined by the Number class accepts an optional argument that specifies a radix, or base, for the conversion. If not specified the conversion is done in base 10.

● Example– var n = 17;– binary_string = n.toString(2); // Evaluates to "10001"– octal_string = "0" + n.toString(8); // Evaluates to "021"– hex_string = "0x" + n.toString(16); // Evaluates to "0x11"

Math Object

● JavaScript supports more complex mathematical operations through a set of functions and constants defined as properties of the Math object

Math functions and Properties

● Math.pow(2,53) //=> 9007199254740992: 2 to the power 53● Math.round(.6) //=> 1.0: round to the nearest integer● Math.ceil(.6) //=> 1.0: round up to an integer● Math.floor(.6) //=> 0.0: round down to an integer● Math.abs(-5) //=> 5: absolute value● Math.max(x,y,z) //Return the largest argument● Math.min(x,y,z) //Return the smallest argument● Math.random() //Pseudo-random number 0 <= x < 1.0● Math.PI // π● Math.E // e: The base of the natural logarithm

Math functions and Properties

● Math.sqrt(3) // The square root of 3● Math.pow(3,1/3) // The cube root of 3● Math.sin(0) // Trig: also Math.cos, Math.atan, etc.● Math.log(10) // Natural logarithm of 10● Math.log(100)/Math.LN10 // Base 10 logarithm of 100● Math.log(512)/Math.LN2 // Base 2 logarithm of 512● Math.exp(3) // Math.E cubed

Infinity

● Arithmetic in JavaScript does not raise errors in cases of overflow, underflow, or division by zero.

● When the result of a numeric operation is larger than the largest representable number (overflow), the result is Infinity.

● Similarly, when a negative value becomes larger than the largest representable negative number, the result is negative infinity, printed as -Infinity.

● When adding, subtracting, multiplying, or dividing Infinity by anything results in an infinite value (possibly with the sign reversed).

NaN

● The not-a-number value has a feature in JavaScript: it does not compare equal to any other value, including itself.

● x == NaN to determine whether the value of a variable x is NaN. Instead, you should write x != x, returns true if, and only if, x is NaN.

● The function – isNaN() - returns true if its argument is NaN, or if that argument is

a nonnumeric value such as a string or an object.

– isFinite() returns true if its argument is a number other than NaN, Infinity, or -Infinity

Type Conversions

● Implicit Conversion– Boolean conversion as false for :

● undefined● null● 0● -0● NaN● "" // the empty string

– Boolean conversion to true - All other values, including all objects (and arrays)

Type Conversions

● Implicit Conversion - Examples– 10 + " objects" // => "10 objects". 10 -> string

– "7" * "4" // => 28: both strings -> numbers

– var n = 1 – "x"; // => NaN: "x" can't convert to a number

– n + " objects" // => "NaN objects": NaN -> "NaN"

– Following comparisons are true, after conversion● null == undefined //These two are treated as equal.● "0" == 0 // String -> a number before comparing.● 0 == false //Boolean -> number before comparing.● "0" == false //Both operands -> 0 before comparing.

Type Conversions

● Implicit Conversion● If one operand of the + operator is a string, it converts the other

one to a string.● The unary + operator converts its operand to a number. ● And the unary ! operator converts its operand to a boolean and

negates it.● Examples

– x + "" // Same as String(x)

– +x // Same as Number(x).

– x-0 // Same as Number(x).

– !x // Same as Boolean(x)

Type Conversions

● Explicit Conversion – done using the Boolean(), Number(), String(), or Object() functions:– Number("3") // => 3

– String(false) // => "false" Or false.toString()

– Boolean([]) // => true

– Object(3) // => new Number(3)

Undeclared Variables

● Assigning a value to an undeclared variable, Java-Script actually creates that variable as a property of the global object, and it works like a properly declared global variable

● Best Practise – to declare the variables using 'var'

Array Objects

● Arrays are supported as objects.● Attribute length● Methods include: concat, join, pop, push,

reverse, sort

EIW: Javascript the Language 42

Some similarity to C++

• Array indexes start at 0.• Syntax for accessing an element is the

same:a[3]++;

b[i] = i*72;

EIW: Javascript the Language 43

New in JS

• Arrays can grow dynamically – just add new elements at the end.

• Arrays can have holes, elements that have no value.

• Array elements can be anything– numbers, strings, or arrays!

EIW: Javascript the Language 44

Creating Array Objects

• With the new operator and a size:

var x = new Array(10);• With the new operator and an initial set

of element values:

var y = new Array(18,”hi”,22);• Assignment of an array literal

var x = [1,0,2];

EIW: Javascript the Language 45

Arrays and Loops

var a = new Array(4);

for (i=0;i<a.length;i++) { a[i]=i;}

for (j in a) { document.writeln(j);}

EIW: Javascript the Language 46

Array Example

var colors = [ “blue”,

“green”,

“yellow];

var x = window.prompt(“enter a number”);

window.bgColor = colors[x];

EIW: Javascript the Language 47

Array of Arrays

• Javascript does not support 2-dimensional arrays (as part of the language).

• BUT – each array element can be an array.

• Resulting syntax looks like C++!

EIW: Javascript the Language 48

Array of Arrays Example

var board = [ [1,2,3],

[4,5,6],

[7,8,9] ];

for (i=0;i<3;i++)

for (j=0;j<3;j++)

board[i][j]++;