CNIT 133 - PowerPoint PPT Presentation

1 / 19
About This Presentation
Title:

CNIT 133

Description:

A function is a block of JavaScript code that is defined once but may be invoked, ... function hypotenuse(a, b) { function square(x) { return x * x; ... – PowerPoint PPT presentation

Number of Views:23
Avg rating:3.0/5.0
Slides: 20
Provided by: hy86
Category:
Tags: cnit | hypotenuse

less

Transcript and Presenter's Notes

Title: CNIT 133


1
CNIT 133
  • Functions

2
Objectives
  • JavaScript Functions
  • Defining and Invoking Functions
  • Function Arguments
  • Functions as Data
  • Functions as Methods
  • Constructor Functions
  • Function Properties and Methods

3
Functions
  • A function is a block of JavaScript code that is
    defined once but may be invoked, or executed, any
    number of times.
  • Functions may have parameters, or arguments
    local variables whose value is specified when the
    function is invoked.
  • Functions often use these arguments to compute a
    return value that becomes the value of the
    function invocation expression.
  • When a function is invoked on an object, the
    function is called a method, and the object on
    which it is invoked is passed as an implicit
    argument of the function.

4
Defining and Invoking Functions
  • The most common way to define a function is with
    the function statement.
  • This function consists of the function keyword
    followed by
  • The name of the function
  • Zero or more parameter names contained within
    parenthesis, each separated by commas
  • The JavaScript statements that comprise the body
    of the function, contained within curly braces
  • function print(msg)
  • document.write(msg ltbrgt)
  • function factorial(x)
  • if (x lt 1)
  • return 1
  • return x factorial(x 1)
  • Once a function has been defined, it may be
    invoked with the () operator.
  • The parentheses appear after the name of the
    function and that an optional comma-separated
    list of argument values or expressions appears
    within the parentheses
  • print(Hello, name)
  • print(Welcome to my web)
  • print(The probability of that is
    factorial(5)/factorial(13))

5
Nested Functions
  • In JavaScript, functions may be nested within
    other functions
  • function hypotenuse(a, b)
  • function square(x) return x x
  • return Math.sqrt(square(a) square(b))
  • Nested functions may be defined only at the top
    level of the function within which they are
    nested (i.e. they may not be defined within
    statement blocks, or while loop)(this restriction
    applies only to functions defined with the
    function statement)
  • Function literal expression may appear anywhere.

6
Function Literals
  • JavaScript allows functions to be defined with
    function literals.
  • A function literal is an expression that defines
    an unnamed function.
  • The syntax for a function literal is much like
    that of the function statement, except that it is
    used as an expression rather than as a statement
    and no function name is required.
  • function f(x) return x x // function
    statement
  • var f function(x) return x x //
    function literal
  • Function literals create unnamed functions which
    is useful when writing recursive functions that
    call themselves
  • var f function fact(x) if (x lt 1) return 1
    else return x fact(x 1)
  • Function literal expression can be stored into a
    variable, passed to another function, or even
    invoked directly
  • f0 function(x) return x x // define
    a function and store it
  • a.sort(function(a,b) return a b) //
    define a function, pass it to another
  • var tensquared (function(x) return x
    x)(10) // define and invoke

7
Naming Functions
  • Any legal JavaScript identifier can be a function
    name.
  • When a name includes multiple words, one
    convention is to separate words with underscores
    like_this()
  • Another convention is to begin all words after
    the first with an uppercase letter likeThis().
  • Functions that are supposed to be internal or
    hidden are sometimes given names that begin with
    an underscore.

8
Function Arguments
  • JavaScript functions can be invoked with any
    number of arguments, regardless of the number of
    arguments named in the function definition.
  • Function is loosely typed, it is legal to pass
    values of any type to any function.

9
Optional Arguments
  • When a function is invoked with fewer arguments
    than are declared, the additional arguments have
    the undefined value.
  • It is often useful to write functions so that
    some arguments are optional and may be omitted
    when the function is invoked
  • // append the names of the enumerable properties
    of object
  • // o to the array a, and return a. If a is
    omitted or null, create
  • // and return a new array.
  • function copyPropertyNamesToArray(o, / optional
    / a)
  • if (!a) a // if undefined or null, use
    a blank array
  • for (var property in o) a.push(property)
  • return a
  • With the function defined this way, you have
    flexibility in how it is invoked
  • // get property names of objects o and p
  • var a copyPropertyNamesToArray(o)
  • copyPropertyNamesToArray(p,a)

10
Variable-Length Argument Lists The Argument
Object
  • Within the body of a function, the identifier
    arguments has special meaning.
  • Arguments is a special property that refers to an
    object known as the Arguments object
  • The Arguments object is an array-like object that
    allows the argument values passed to the function
    to be retrieved by number, rather than by name.
  • The Arguments object also defines an additional
    callee property.
  • Although a JavaScript function is defined with a
    fixed number of named arguments, it can be passed
    any number of arguments when it is invoked.
  • The Arguments object allows full access to these
    argument values, even when some of all are
    unnamed (argument0, argument1, etc)
  • function f(x, y, z)
  • if (arguments.length ! 3)
  • throw new Error(function f called with
    arguments.length
  • arguments, but it expects 3 arguments.)
  • // actual function

11
Variable-Length Argument Lists The Argument
Object
  • The arguments object also open up an important
    possibility for JavaScript functions they can be
    written so that they work with any number of
    arguments
  • function max(/ /)
  • var m Number.NEGATIVE_INFINITY
  • for (var i 0 i lt arguments.length i)
  • if (argumentsi gt m) m argumentsi
  • return m
  • Functions like this one that can accept any
    number of arguments are called variadic
    functions, variable arity functions, or varargs
    functions.

12
The callee Property
  • The Arguments object defines a callee property
    that refers to the function that is currently
    being executed.
  • This property is rarely useful, but it can be
    used to allow unnamed functions to invoke
    themselves recursively
  • function(x)
  • if (x lt 1) return 1
  • return x arguments.callee(x 1)

13
Argument Types
  • Since JavaScript is loosely typed, method
    arguments have no declared types, and no type
    checking is performed on the values you pass to a
    function.
  • You can self-documenting by including argument
    types in comments.
  • For arguments that are optional, you can include
    the word optional in the comment
  • When a method can accept any number of arguments,
    you can use an ellipsis.
  • If you write a function that expects a string
    argument and then call that function with a value
    of some other type, the value you passed will
    simply be converted to a string when the function
    tries to use it as a string.
  • All primitive types can be converted to strings,
    and all objects have toString() methods.

14
Functions as Data
  • In JavaScript, functions are not only syntax but
    also data, they can be assigned to variables,
    stored in the properties of objects or the
    elements of arrays, passed as arguments to
    functions, and so on
  • function square(x) return x x
  • This definition creates a new function object and
    assigns it to the variable square. The function
    can be assigned to another variable
  • var a square(4) // a contains square of 4
  • var b square // b refers to function square
  • var c b(5) // c contains result of square 5
  • Functions can also be assigned to object
    properties
  • var o new Object
  • o.square function(x) return x x //
    function literal
  • y o.square(3) // y contains result of square
    3
  • Functions can also be assigned to array elements
  • var a new Array(3)
  • a0 function(x) return x x
  • a1 5
  • a2 a0(a1) // a2 contains result of
    square 5

15
Functions as Methods
  • A method is nothing more than a JavaScript
    function that is stored in a property of an
    object and invoked through that object.
  • If you have a function f and an object o, you can
    define a method name m
  • o.m f
  • Having defined the method m() of the object o,
    invoke it like this
  • o.m()
  • o.m(x, x2) // if m() requires two arguments
  • Methods have one very important property the
    object through which a method is invoked becomes
    the value of the this keyword within the body of
    the method.
  • Thus, when you invoke o.m(), the body of the
    method can refer to the object o with the this
    keyword
  • var calculator // an object literal
  • operand1 1,
  • operand2 2,
  • compute function()
  • this.result this.operand1 this.operand2
  • calculator.compute()
  • alert(calculator.result) // display the result

16
Constructor Functions
  • A constructor function is a function that
    initializes the properties of an object and is
    intended for use with the new operator.

17
Functions Properties and Methods
  • The typeof operator returns the string function
    when applied to a function, but functions are
    really a specialized kind of JavaScript object.
  • Since functions are objects, they have properties
    and methods.

18
The length Property
  • The length property of the arguments array
    specifies the number of arguments that were
    passed to the function. (arguments.length)
  • The length property of a function itself, is a
    read-only property, returns the number of
    arguments that the function expects to be passed
    that is, the number of parameters it declares
    in its parameter list. (arguments.callee.length)
  • function check(args)
  • var actual args.length // actual
    number of arguments
  • var expected args.callee.length // expected
    number of arguments
  • if (actual ! expected)
  • throw new Error(Wrong number of arguments
    expected expected actual passed
    actual)

19
Defining Your Own Function Properties
  • Advanced topic
  • When a function needs to use a variable whose
    value persists across invocations, it is often
    convenient to use a property of the Function
    object, instead of cluttering up the namespace by
    defining a global variable.
  • // create and initialize the static variable
  • uniqueInteger.counter 0
  • // the function, returns a diff value each time
  • function uniqueInteger()
  • return uniqueInteger.counter
Write a Comment
User Comments (0)
About PowerShow.com