10.JavaScript Objects

download 10.JavaScript Objects

of 74

Transcript of 10.JavaScript Objects

  • 8/4/2019 10.JavaScript Objects

    1/74

    JavaScript Objects

    Arrays

    Objects

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    2/74

    Objectives Arrays

    Introduction

    Passing Array to Function

    Multiple subscripts

    Objects Introduction

    Math Object

    String Object

    Date Object

    Boolean and Number Object

    Creating Objects

    Dynamic HTML Introduction

    Properties

    Object Referencing

    Collection all and children

    Dynamic styles, positioning, navigator Object

    DHTML Object Model

    Summary

  • 8/4/2019 10.JavaScript Objects

    3/74

    ArraysIntroduction

    Array is a grouping of objects that can be accessed

    through subscripts Arrays are useful for storing data of similar types Unlike in some languages, values in JavaScript arrays do

    not all have to be of the same data type

    In JavaScript, the first element of an array is considered tobe at position zero

    Syntax

    Arrays are declared using the new keyword

    var variables_name = new Array(); The [] literal is used to declare a new Array object

    var variables_name = [];

    Can be declared with initial values var var_name = new Array (values_list_separated_comma);

    var var_name = [values_list_separated_comma]

  • 8/4/2019 10.JavaScript Objects

    4/74

    ArraysIntroductionExample

  • 8/4/2019 10.JavaScript Objects

    5/74

    ArraysIntroductionExample

  • 8/4/2019 10.JavaScript Objects

    6/74

    ArraysIntroductionExample

  • 8/4/2019 10.JavaScript Objects

    7/74

    rraysIntroduction

    Whereas regular (or enumerated) arrays are indexed

    numerically, associative arrays are indexed using

    names as keys.

    The advantage of this is that the keys can be meaningful,

    which can make it easier to reference an element in anarray

    Some useful array properties and methods are

    usedProperty Descriptionslength Holds the number of elements in an array

  • 8/4/2019 10.JavaScript Objects

    8/74

    rraysIntroduction

    Props/Methods Descriptions

    join(delimiter)Returns a delimited list of the items indexed with integers in the

    array. The default delimiter is a comma

    pop() Removes the last item in an array and returns its value

    shift() Removes the first item in an array and returns its value

    slice(start, end)

    Returns a subarray from start to end. If end is left out, it includes

    the remainder of the array.

    splice(start, count)Removes count items from start in the array and returns the

    resulting array

    sort ([arguments])

    If no arguments, JavaScript uses string comparisons to determine

    sorting order. Otherwise,

    -Takes the name of a function called the comparator function

    -Comparator function takes two arguments and returns

    - A negative value if the 1st argument is less than the 2nd

    - Zero if the arguments are equal

    - A positive value if the 1st argument is greater than the 2nd

  • 8/4/2019 10.JavaScript Objects

    9/74

    ArraysIntroductionExample

    A

  • 8/4/2019 10.JavaScript Objects

    10/74

    ArraysIntroductionExample

    A

  • 8/4/2019 10.JavaScript Objects

    11/74

    ArraysPassing Arrays to Functions

    To pass an array to a function

    Specify the name of the array without brackets as a parameter Do not need to separately pass the size of the array

    Individual numeric and boolean array elements are

    Passed exactly as simple numeric and boolean variables: call-by-

    value

    Simple single pieces of data are called scalars or scalar qualities

    Are passed using subscripted name of the array element

    For function to receive Array through a function call Must specify parameter that will be used to refer to the array in the

    body of the function

    A

  • 8/4/2019 10.JavaScript Objects

    12/74

    ArraysPassing Arrays to FunctionsExample

    A

  • 8/4/2019 10.JavaScript Objects

    13/74

    ArraysPassing Arrays to FunctionsExample

    A

  • 8/4/2019 10.JavaScript Objects

    14/74

    ArraysPassing Arrays to FunctionsExample

    A

  • 8/4/2019 10.JavaScript Objects

    15/74

    ArraysMultiple subscripts

    JavaScript support mutli-dimensional array

    Double-subscripted array (or two-dimensional arrays) Require two subscripts to identify a particular element

    First subscript identifies elements row

    Second subscript identifies elements column

    m-by-n array An array with m rows and n columns

    Initialization Declared like a single-scripted array

    Ex:

    var b = [ [ 1, 2 ], [ 3, 4 , 5] ];

    Compiler determines number ofelements in row/column

    By counting number of initializer values in sub-initializer list for thatrow/column

    Can have a different number of columns in each row

    for and for/in loops used to traverse the arrays Manipulate every element of the array

    A

  • 8/4/2019 10.JavaScript Objects

    16/74

    ArraysMultiple subscriptsExample

    Obj t

  • 8/4/2019 10.JavaScript Objects

    17/74

    ObjectsIntroduction

    Objects are the fundamental unit of code encapsulation and

    reuse in any OO language. It is incredibly easy to create objects in JavaScript

    JavaScript is an object-based programming language

    JavaScript is used to manipulate or get information about

    objects in the HTML DOM. Objects in an HTML page have

    Methods (actions, such as opening a new window or submitting aform)

    And, properties (attributes or qualities, such as color and size).

    JavaScript has some predefined, built-in objects that

    Do not fit into the HTML DOM

    Are not direct descendants of the window object.

    Obj t

  • 8/4/2019 10.JavaScript Objects

    18/74

    ObjectsMath

    Is a built-in static object.

    Their properties and methods are accessed directly and areused for performing complex math operations

    Some properties

    Constant Description Value

    Math.E Eulers constant. Approximately 2.718.

    Math.LN2 Natural logarithm of 2. Approximately 0.693.

    Math.LN10 Natural logarithm of 10. Approximately 2.302.

    Math.LOG2E Base 2 logarithm of

    Eulers constant.

    Approximately 1.442.

    Math.LOG10E Base 10 logarithm of

    Eulers constant.

    Approximately 0.434.

    Math.PI PI - ratio of circlescircumference to its

    diameter.

    Approximately

    3.141592653589793.

    Math.SQRT1_2 Square root of 0.5. Approximately 0.707.

    Math.SQRT2 Square root of 2.0. Approximately 1.414.

    Obj

  • 8/4/2019 10.JavaScript Objects

    19/74

    ObjectsMathMethods

    Methods Descriptions

    abs (x) Absolute value of x

    ceil (x) Rounds x to the next highest integer

    cos (x) Trigonometric cosine of x (x is radians)

    floor (x) Rounds x to the next lowest integer

    log (x) Natural logarithm of x (base e)

    max (x, y) Larger value of x and y

    min (x, y) Smaller value of x and y

    pow (x, y) x raised to power y

    round (x) Rounds x to the closest integer

    sin (x) Trigonometric sine of x (x is radians)

    sqrt (x) square root of x

    tan (x) Trigonometric tangent of x (x is radians)

    random () Random number between 0 and 1.

    Obj t

  • 8/4/2019 10.JavaScript Objects

    20/74

    ObjectsString

    In JavaScript, there are two types of string data types: primitivestrings and String objects.

    String objects have many methods for manipulating and parsingstrings of text. Because these methods are available to primitive strings as well, in practice,

    there is no need to differentiate between the two types of strings

    Characters are fundamental building blocks of JavaScript programs

    A string is series ofCharacters treated as a single unit

    It may include letters, digit, and various special characters,

    String Object is JavaScripts string and character processing capabilities

    Encapsulates the attributes and behaviors of a string of characters

    String literals or string constant are written as sequence ofcharacters in single or double quotation marks

    Strings may be compared with Relational operators

    ects

  • 8/4/2019 10.JavaScript Objects

    21/74

    ectsStringMethods

    Methods Descriptions

    charAt(position) Returns the character at the specified position

    charCodeAt(position)Returns the Unicode character code of the character at the

    specified position

    concat (string)Concatenates its argument to the end of the string. The

    original strings are not modified

    fromCharCode

    (characterCodes)

    Returns the text representation of the specifies comma-

    delimited character codes. Used with String rather than a

    specific String object

    indexOf(substring,

    startPosition)

    Searches from startPosition for substring. Returns the

    position at which the substring is found. If substring is notfound, returns -1

    lastIndexOf(substring,

    endPosition)

    Searches from the end of the string for substring until

    endPosition is reached. Returns the position at which the

    substring is found. If substring is not found, returns -1.

    ects

  • 8/4/2019 10.JavaScript Objects

    22/74

    ectsStringMethods

    Methods Descriptions

    substring(startPosition

    , endPosition)

    Returns the substring beginning at startPosition and endingwith the character before endPosition. endPosition is

    optional. If it is excluded, the substring continues to the end

    of the string.

    substr(startPosition,length)

    Returns the substring of Length characters beginning at

    startPosition. length is optional. If it is excluded, thesubstring continues to the end of the string

    slice(startPosition,

    endPosition)Same as substring(startPosition, endPosition).

    slice(startPosition,positionFromEnd)

    positionFromEnd is a negative integer. Returns the thesubstring beginning at startPosition and ending

    positionFromEnd characters from the end of the string.

    split(delimiter)Returns an array by splitting a string on the specified

    delimiter.

    toLowerCase() Returns the string in all lowercase letters.

    ects

  • 8/4/2019 10.JavaScript Objects

    23/74

    ectsStringMethods

    Methods Descriptions

    toUpperCase() Returns the string in all uppercase letters

    toString() Returns the same string as the source string

    valueOf() Returns the same string as the source string.

    Objects

  • 8/4/2019 10.JavaScript Objects

    24/74

    ObjectsStringHTML Markup Methods

    When a markup method is applied to a string, the

    string is automatically wrapped in the

    appropriate HTML tag

    These methods are particularly useful for

    generating HTML dynamically during scripting

    processing

    Objects

  • 8/4/2019 10.JavaScript Objects

    25/74

    ObjectsStringHTML Markup Methods

    Method Description

    anchor(name )

    Wraps source string in anchor elementwithname as anchor name.

    big() Wraps source string in aelement.

    blink() Wraps source string in aelement.bold() Wraps source string in aelement.

    fixed() Wraps source string in aelement.

    fontcolor( color ) Wraps source string in aelement with

    coloras the font color.

    fontsize( size ) Wraps source string in aelement with

    size as HTML font size.

    italics() Wraps source string in anelement.

    link( url )Wraps source string in anwith

    urlas thehyperlink location.

    small() Wraps source string in aelement.

    strike() Wraps source string in a

    element.

    sub() Wraps source string in aelement.

    sup() Wraps source string in aelement.

    Objects

  • 8/4/2019 10.JavaScript Objects

    26/74

    ObjectsStringHTML Markup MethodsExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    27/74

    ObjectsStringHTML Markup MethodsExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    28/74

    ObjectsDate

    Has methods for manipulating dates and times.

    JavaScript stores dates as the number of milliseconds sinceJanuary 1, 1970

    Date and time processing can be performed based on

    Local time zone

    Universal Coordinated Time (UTC) /Greenwich Mean Time (GMT)

    Most methods in Date object have local time zone and UTC versions

    To create a Date object containing the current date and time, theDate() constructor takes no arguments

    When passing the date as a string to the Date() constructor, the timeportion is optional.

    If it is not included, it defaults to 00:00:00.

    Other date formats are acceptable (ex: "10/21/2004" and "10-04-2004").

    When passing date parts to the Date() constructor, dd, hh, mm, ss, and ms are all optional. The default of each is 0.

    Months are numbered from 0 (January) to 11 (December)

    Objects

  • 8/4/2019 10.JavaScript Objects

    29/74

    ObjectsDate

    Two other methods can be called without creating new

    Date object Both methods return number of milliseconds between midnight,

    January 1, 1970 and date specified by argument

    Either method can be converted to a Date object

    var theDate = new Date(numberOfMilliseconds);

    numberOfMilliseconds equals the result of Date.UTC or Date.Parse

    Date.parse(argument);

    argument: short date or long date

    Date.UTC(argument); argument: same for as date construct (Y, M, D, H, M, S, M)

    Other methods should be reference at Fig 18.8 (textbook e-

    business and e-commerce How to program, Deitel, Deitel

    & Nieto)

    b ects

  • 8/4/2019 10.JavaScript Objects

    30/74

    b ectsDateExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    31/74

    ObjectsDateExample

    b ects

  • 8/4/2019 10.JavaScript Objects

    32/74

    b ectsDateExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    33/74

    ObjectsBoolean and Number

    Provided Boolean and Number object as object wrappers

    These wrappers define methods and properties useful inmanipulating boolean values and numbers

    Number object JavaScript automatically creates Number objects to store numeric values

    Programmers can create a Number object with

    var n = new Number( numericValue );

    For other Number object methods, see figure 18.11 (textbook e-business and e-commerceHow to program, Deitel, Deitel & Nieto)

    Boolean object When boolean value required in a program, automatically created by JavaScript

    to store the value using Boolean object

    Programmers can create Boolean objects explicitly

    var b = new Boolean( booleanValue );

    If boolean value equals false, 0, null, Number.NaN or empty string ( )

    Boolean object contains false

    Otherwise, Boolean Object contains true

    Objects

  • 8/4/2019 10.JavaScript Objects

    34/74

    ObjectsCreating Objects

    There are various ways to create or declare object

    Create an empty object and progressively add its properties andmethods

    var Obj_name = {};

    Obj_name.property_name = value;

    Obj_name.method_name = function ([arguments]) {

    //statements;

    };

    Use a literal notation for objects

    var Obj_name = {

    property_name: value,

    function_name: function ([arguments]) {

    //statement

    };

    };

    Objects

  • 8/4/2019 10.JavaScript Objects

    35/74

    ObjectsCreating Objects

    There are various ways to create or declare object (cont)

    Using factory functions: just encapsulate that logic in a functionfunction function_name (arguments) {

    //Create an empty object and progressively add its properties and methods

    return object_name;

    }

    Usage: var var_name = function_name(parameters);

    Constructor

    In JavaScript, when function is called preceded by the new

    operator, the function receives an implicit this argument that is a

    brand new object, ready to be assembled with properties and

    methods.

    Also, ifwe do not return anything explicitly, the new operator

    automatically returns this

    Objects

  • 8/4/2019 10.JavaScript Objects

    36/74

    ObjectsCreating ObjectsExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    37/74

    ObjectsCreating ObjectsExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    38/74

    ObjectsCreating ObjectsExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    39/74

    ObjectsCreating ObjectsExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    40/74

    ObjectsCreating ObjectsExample

    Objects

  • 8/4/2019 10.JavaScript Objects

    41/74

    ObjectsCreating ObjectsExample

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    42/74

    Dynam c HTMLIntroduction

    Is not a technology in and of itself, but rather is acombination of three technologies: HTML, CascadingStyle Sheets (CSS), and JavaScript. Involves using JavaScript to change a CSS property of an HTML

    element.

    Helps Web application developers produce more

    responsive data-intensive applications With DHTML, IE enables processing to begin immediately after

    a portion of large amount of data arrives

    Some manipulations can be done directly on the client withoutinvolving the server and the network

    In modern browsers, most CSS properties can be modifieddynamically. Change an individual style of element (using the style property)

    Change the class name assigned to the element (using theclassName property).

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    43/74

    Dynam c HTMLProcessing

    Accessing and Modifying Styles The style object is a collection of an element's styles that are either

    defined within that HTML element's style attribute or directly inJavaScript.

    Styles defined in the tag or in an external style sheet arenot part of the style object.

    The window object's getComputedStyle() method (in Mozilla) or

    the currentStyle property (IE) is used to get the current style of anobject

    Syntax varName = window.getComputedStyle(Element, Pseudo-Element)

    varName = Element.currentStyle.Property

    Element.style.property_name = value

    Hiding and Showing Elements Elements can be hidden and shown by changing their visibility or

    display values.

    The visibility style can be set to visible/hidden and the displayproperty can be set to block, table-row, none, several other values

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    44/74

    Dynam c HTMLProcessingExample

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    45/74

    Dynam c HTMLProcessingExample

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    46/74

    Dynam c HTMLProperties

    The innerHTML property can be used to read and set the

    HTML content of an element

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    47/74

    Dynam c HTMLPropertiesExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    48/74

    Dynamic HTMLProperties

    HTML tables can be created and manipulated

    dynamically with JavaScript. Each table element contains a rows array and methods for

    inserting and deleting rows insertRow() and deleteRow().

    Each tr element contains a cells array and methods for inserting

    and deleting cells insertCell() and deleteCell().

    The dimensions of an object can be changed by modifyingthe width and height properties of the element's style

    property Element.style.width

    The z-index of an object can be changed by modifying thezIndex property of the element's style property

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    49/74

    Dynam c HTMLPropertiesExample

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    50/74

    Dynam c HTMLPropertiesExample

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    51/74

    Dynam c HTMLPropertiesExample

    Dynam c HTML

  • 8/4/2019 10.JavaScript Objects

    52/74

    Dynam c HTMLObject Referencing

    Simplest way to reference an element is by its ID attribute

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    53/74

    Dynamic HTMLObject ReferencingExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    54/74

    Dynamic HTMLCollections all and children

    Collections are basically arrays of related objects on a

    page The Dynamic HTML Object Model includes a special

    collection, all The all collection is collection of all the HTML elements in a

    document in the order in which they appear

    This provides an easy way ofreferring to any specific element,especially ifit does not have an ID

    The length property specifies the number of elements in thecollection

    The tagName property of an element determines the name ofthe element

    The children collection Contains only those elements that are direct child elements of

    that element

    Is used to walk through all the elements in the document

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    55/74

    Dynamic HTMLCollections all and childrenExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    56/74

    y a cCollections all and childrenExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    57/74

    y aCollections all and childrenExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    58/74

    yCollections all and childrenExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    59/74

    yDynamic Styles

    All elements style can be changed dynamically

    Dynamic HTML object model allows to change theCLASS attribute of an element Instead of changing many individual styles at a time, the style

    classes have supported easily altering element styles

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    60/74

    yDynamic StylesExample

    b ect ModelD i S l E l

  • 8/4/2019 10.JavaScript Objects

    61/74

    Dynamic StylesExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    62/74

    yDynamic StylesExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    63/74

    yDynamic Positioning

    An element can be positioned with scripting using CSS position

    property

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    64/74

    yDynamic PositioningExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    65/74

    yDynamic PositioningExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    66/74

    yUsing the frames Collection

    To reference a frame, use frames(name) where name is the ID or

    NAME of the desired frame Use a name as a namespace

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    67/74

    yUsing the frames CollectionExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    68/74

    yUsing the frames CollectionExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    69/74

    ynavigator Object

    Is supported by Netscape Navigator and Internet Explorer Contains info about the Web browser viewing the page

    navigator.appName contains the name of the application

    Value of navigator.appVersion not a simple integer

    contains other info, such as OS

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    70/74

    ynavigator ObjectExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    71/74

    ynavigator ObjectExample

    Dynamic HTML

  • 8/4/2019 10.JavaScript Objects

    72/74

    The DHMTL Object Modelwindow

    document

    history

    navigator

    applets

    all

    anchors

    body

    embeds

    forms

    filters

    images

    links

    plugins

    styleSheets

    scripts

    location

    screen

    event

    document

    document

    plugins

    object

    collection

    Key

    frames

  • 8/4/2019 10.JavaScript Objects

    73/74

    Summary

    Arrays

    Objects

    Dynamic HTML

    Q&A

    Next Lecture

  • 8/4/2019 10.JavaScript Objects

    74/74

    Next Lecture

    Dynamic HTML

    Event Model

    Filters and Transitions

    Data Binding with Tabular Data Control