MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Chapter 7: User-Defined Functions II
Lecture 16 Subroutine Calls and Parameter Passing Semantics Dragon: Sec. 7.5 Fischer: Sec Procedure declaration procedure p( a, b : integer, f :
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
The Web Warrior Guide to Web Design Technologies
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
SchemeCOP Introduction to Scheme. SchemeCOP Scheme Meta-language for coding interpreters –“ clean ” semantics Scheme = LISP + ALGOL –simple.
 Pearson Education, Inc. All rights reserved Arrays.
Inline Function. 2 Expanded in a line when it is invoked Ie compiler replace the function call with function code To make a function inline the function.
OBJECTS MIT-AITI copyright Introduction Object and Properties Constructors and Methods Prototypes and Inheritance Object-Oriented JavaScript Objects.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
1 CS101 Introduction to Computing Lecture 29 Functions & Variable Scope (Web Development Lecture 10)
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Topics Scope Scope and Lifetime Referencing Environments.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Tutorial 2 Variables and Objects. Working with Variables and Objects Variables (or identifiers) –Values stored in computer memory locations –Value can.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
JavaScript, Fourth Edition
Function the Ultimate Act III. Function Method Class Constructor Module.
Julian on JavaScript: Functions Julian M Bucknall, CTO.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Objects.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Unit 10-JavaScript Functions Instructor: Brent Presley.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
JavaScript for C# developers Dhananjay Microsoft MVP
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Methods.
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
JavaScript and Ajax (JavaScript Functions) Week 5 Web site:
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
 2005 Pearson Education, Inc. All rights reserved Arrays.
Chapter VII: Arrays.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 3 OF 3
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Modern JavaScript Develop And Design
JavaScript: Functions
Scope, Objects, Strings, Numbers
Functions Declarations, Function Expressions and IIFEs
User-Defined Functions
CHAPTER FOUR Functions.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CS5220 Advanced Topics in Web Programming JavaScript Basics
Predefined Functions Revisited
Corresponds with Chapter 5
Presentation transcript:

MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function properties and Methods

Defining and Invoking Functions function Keyword Followed by name of function, list of parameters, and JavaScript statements contained within curly braces. Functions can have a return statement which causes it to stop executing and return the value of its expression

Example 1 Generic Form: function name(arg1, arg2) { statements; } Example: function write(msg) { document.write(msg + ” ”); }

Invoking functions Once a method is defined it is invoked using the () operator For example to invoke the previously defined method we would type the following write(“Hello,” + name); Note that within the parenthesis are the arguments which are separated by a comma if there are many.

More on Invocation Each expression specified between the parenthesis is evaluated and the resulting value used as an argument JavaScript is an untyped language You can determine the type by using the typeof operator On invocation the number of arguments are not checked. If more, the extra ones are ignored. If fewer the missing arguments are assigned undefined values

Nested Functions Function definition can occur within other function definitions Javascript uses lexical/Static scoping I.e. Functions are executed using the scope chain that was in effect when they were defined

Example 2 function SNR(stdev) { function square(x) {return x* x;} return 1/square(stdev); }

Function() Constructor Another way to create functions- makes use of the new operator e.g var f = new Function(“x”,“y”,“return x*y”); Function constructor expects any number of string arguments The last argument contains the body of the function whilst the other arguments specify the name of the parameters to the function being defined

Function() continued The Function() constructor has no argument that specifies the name of the function created. Anonymous functions Function() constructor allows us to build functions dynamically However, requires compilation each time its executed

Function Literals Yet another way to create functions A function literal is an expression that creates an unnamed lambda function Syntax is similar to that for the function statement except that its used as an expression and it has no name

Example 3 Function Literal; Var f = function(x){ return x*x} compare with Function Statement; function f(x) {return x*x;}

Function Literals continued; Suited for functions that are used only once. Functions specified by a function literal expression can be stored into a variable, passed to another function, or even invoked directly:

Example 4 a[0] = function(x) { return x*x;} //Define function and store it. a.sort(function(a,b) {return a-b;}); //Define a function; pass it to another. var tensqaured = (function(x) {return x*x;})(10); //Define and invoke. What is the advantage of using a Function literal over the Function() command

Functions as data Functions in Javascript are data and are therefore treated as any other data value. I.e they can be assigned to variables, stored in properties of objects or the elements of arrays: Operations performed on data can therefore be performed on functions

Example 5 function square(x) {return x*x;} this creates a new function object and assigns it the name square. We assign it to another variable and note it works in the same way b=square;//b now refers to the same function as square does c=b(5); // c has the value 25

Example 6 Functions can be assigned to Object properties rather than global variables o = new Object(); o.square = new Function(“x”,“return x*x”); // Note Function() constructor y=o.square(16);

Example 7 functions don’t require names as when they are assigned to array elements a= new array (10); a[0] = function(x) {return x*x;} // Note function literal a[1] = 20; a[2]= a[0](a[1]); a[2] contains 400

Function Scope The body of a Javascript function executes in a local scope that differs from the Global scope Local variables declared with the var statement are created as properties of the call object and so too are the parameters of the function. In addition to local variables and parameters the call object defines a property called arguments

Function Arguments Arguments is a special property of the call object that refers to an arguments object The above object has a number of properties and also doubles as an array. The arguments[] array hold argument values that were passed to the function.

More on arguments If you invoke a function with two parameters; this can be accessed by the the variables arguments[0] and arguments[1]. The arguments object has a length property that specifies the number of elements it contains. This property is useful in checking if a function is invoked with the correct number of arguments.

Some more on Arguments Two other properties of the argument project are the callee and caller property callee property refers to the function being currently executed. This is useful in allowing unnamed functions to call themselves recursively.

Example 8 function(x) { if(x>1) return x*arguments.callee(x-1); return x; }

And yet more caller property refers to the calling context from which the current function was invoked It does not refer to the function that invoked the current one. To refer to a calling function we must therefore use arguments.caller.callee

Function Properties and Methods The length property of a function returns the number of parameters the function expects to be passed. The length function is available both inside and outside the functions body. Arity is the new property name for length in Navigator 4 This property is useful when determining if correct number of parameters have been passed

Prototype Property Every function has a prototype property that refers to a predefined prototype object: we will learn about this some more in the next chapter You can define your own properties to a function object. This has a direct application when one wants to create static variables for use on the function alone.

Example 9 idno.counter = 0; function idno() { return idno.counter++; }

apply() in Navigator4 this method allows you to invoke a function as if it were a method of another object e.g. f.apply(o, [1,2]); this is similar to, o.m = f; o.m(1,2); delete o.m;

call() in Navigator5 Behaves like apply() except that the arguments to be passed to the function are passed as an argument list as opposed to an array e.g. f.call(o,1,2); //Arguments passed directly in an argument list.