Function the Ultimate Act III. Function Method Class Constructor Module.

Slides:



Advertisements
Similar presentations
PHP functions What are Functions? A function structure:
Advertisements

JavaScript: A Language of Many Contrasts
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Arrays.
Closure Douglas Crockford. Block Scope { let a; { let b; … a … … b … } … a … }
Programming Languages and Paradigms The C Programming Language.
Variables, Environments and Closures. Overview We will Touch on the notions of variable extent and scope Introduce the notions of lexical scope and.
Today Programming Style and Your Brain And Then There Was JavaScript Function the Ultimate The Metamorphosis of Ajax ES5: The New Parts.
JavaScript Training By Effie Nadiv Edited by permission from author by Amir Kirsh Based on work of Douglas Crockford.
© Effie Nadiv JavaScript - Advanced Written by Effie Nadiv, Edited by permission from author by Amir Kirsh Based on work of Douglas Crockford.
Advanced JavaScript Douglas Crockford © 2006 Douglas Crockford.
Julian on JavaScript: Objects Julian M Bucknall, CTO.
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
Access to Names Namespaces, Scopes, Access privileges.
Case, Arrays, and Structures. Summary Slide  Case Structure –Select Case - Numeric Value Example 1 –Select Case - String Value Example  Arrays –Declaring.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
25-Jun-15 JavaScript Language Fundamentals II. 2 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
SchemeCOP Introduction to Scheme. SchemeCOP Scheme Meta-language for coding interpreters –“ clean ” semantics Scheme = LISP + ALGOL –simple.
JAVASCRIPT Introduction Kenny Lam. What is Javascript?  Client-side scripting language that can manipulate elements in the DOM  Event-driven language.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
1 JavaScript: Functions and Arrays October 18, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
Object Oriented Programming
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
C#C# Classes & Methods CS3260 Dennis A. Fairclough Version 1.1 Classes & Methods CS3260 Dennis A. Fairclough Version 1.1.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
1 SystemVerilog Enhancement Requests Daniel Schostak Principal Engineer February 26 th 2010.
CPS120: Introduction to Computer Science Decision Making in Programs.
David Stotts Computer Science Department UNC Chapel Hill.
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Julian on JavaScript: Functions Julian M Bucknall, CTO.
Perl Chapter 6 Functions. Subprograms In Perl, all subprograms are functions – returns 0 or 1 value – although may have “side-effects” optional function.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Objects.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
JavaScript scope and closures
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 for C# developers Dhananjay Microsoft MVP
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Getting from Scripts to Applications Donald J. Sipe | Refresh Jacksonville | November 11 th 2008.
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Click to add Text Javascript Presented by Bunlong VAN Basic.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Constructors and Destructors
Eine By: Avinash Reddy 09/29/2016.
Modern JavaScript Develop And Design
Functions Declarations, Function Expressions and IIFEs
Nested class.
7 Arrays.
Variables, Environments and Closures
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Constructors and Destructors
CS5220 Advanced Topics in Web Programming JavaScript Basics
Namespaces, Scopes, Access privileges
JavaScript: Arrays.
Method of Classes Chapter 7, page 155 Lecture /4/6.
CSE 341 Lecture 11 b closures; scoping rules
CS3220 Web and Internet Programming JavaScript Basics
Presentation transcript:

Function the Ultimate Act III

Function Method Class Constructor Module

function expression function optional name parameters Wrapped in parens Zero or more names Separated by, (comma) body Wrapped in curly braces Zero or more statements

function expression Produces an instance of a function object. Function objects are first class. May be passed as an argument to a function May be returned from a function May assigned to a variable May be stored in an object or array Function objects inherit from Function.prototype.

var statement Declares and initializes variables within a function. Types are not specified. A variable declared anywhere within a function is visible everywhere within the function.

var statement It gets split into two parts: The declaration part gets hoisted to the top of the function, initializing with undefined. The initialization part turns into an ordinary assignment. var myVar = 0, myOtherVar; Expands into var myVar = undefined, myOtherVar = undefined; … myVar = 0;

function statement function mandatory name parameters Wrapped in parens Zero or more names Separated by, (comma) body Wrapped in curly braces Zero or more statements

function statement The function statement is a short-hand for a var statement with a function value. function foo() {} expands to var foo = function foo() {}; which further expands to var foo = undefined; foo = function foo() {}; The assignment of the function is also hoisted!

function expression v function statement If the first token in a statement is function, then it is a function statement.

Scope Block scope v function scope

Scope In JavaScript, { blocks } do not have scope. Only functions have scope. Variables defined in a function are not visible outside of the function. Don’t do this: function assure_positive(matrix, n) { for (var i = 0; i < n; i += 1) { var row = matrix[i]; for (var i = 0; i < row.length; i += 1) { if (row[i] < 0) { throw new Error('Negative'); } }

Declare all variables at the top of the function. Declare all functions before you call them. The language provides mechanisms that allow you to ignore this advice, but they are problematic.

Return statement return expression ; or return; If there is no expression, then the return value is undefined. Except for constructors, whose default return value is this.

Don’t make functions in a loop. It can be wasteful because a new function object is created on every iteration. It can be confusing because the new function closes over the loop’s variables, not over their current values.

Don't create functions in a loop for (var i...) { // WRONG div_id = divs[i].id; divs[i].onclick = function () { alert(div_id); }; } divs.forEach(function (div) { // RIGHT div.onclick = function () { alert(div.id); }; });

Invocation The ( ) suffix operator surrounding zero or more comma separated arguments. The arguments will be bound to parameters.

Invocation If a function is called with too many arguments, the extra arguments are ignored. If a function is called with too few arguments, the missing values will be undefined. There is no implicit type checking on the arguments.

Two pseudo parameters arguments this

arguments When a function is invoked, in addition to its parameters, it also gets a special parameter called arguments. It contains all of the arguments from the invocation. It is an array-like object. arguments.length is the number of arguments passed. Weird interaction with parameters.

Example function sum() { var i, n = arguments.length, total = 0; for (i = 0; i < n; i += 1) { total += arguments[i]; } return total; } var ten = sum(1, 2, 3, 4);

this The this parameter contains a reference to the object of invocation. this allows a method to know what object it is concerned with. this allows a single function object to service many objects. this is key to prototypal inheritance.

Invocation There are four ways to call a function: Function form functionObject ( arguments ) Method form thisObject. methodName ( arguments ) thisObject [" methodName "]( arguments ) Constructor form new FunctionObject ( arguments ) Apply form functionObject.apply( thisObject,[ arguments ])

Method form thisObject. methodName ( arguments ) thisObject [ methodName ]( arguments ) When a function is called in the method form, this is set to thisObject, the object containing the function. This allows methods to have a reference to the object of interest.

Function form functionObject ( arguments ) When a function is called in the function form, this is set to the global object. That is not very useful. (Fixed in ES5/Strict) An inner function does not get access to the outer this. var that = this;

Constructor form new FunctionValue ( arguments ) When a function is called with the new operator, a new object is created and assigned to this. If there is not an explicit return value, then this will be returned. Used in the Pseudoclassical style.

Apply form functionObject.apply( thisObject, arguments ) functionObject.call( thisObject, argument… ) A function’s apply or call method allows for calling the function, explicitly specifying thisObject. It can also take an array of parameters or a sequence of parameters. Function.prototype.call = function (thisObject) { return this.apply(thisObject, Array.prototype.slice.apply(arguments, [1])); };

this this is an bonus parameter. Its value depends on the calling form. this gives methods access to their objects. this is bound at invocation time. Invocation form this function the global object undefined methodthe object constructorthe new object applyargument

Recursion When a function calls itself.

Quicksort 1.Divide the array into two groups, low and high. 2.Call Quicksort on each group containing more than one element.

The Little Lisper

The Little Schemer

Tennent’s Principle of Correspondence function factorial(n) { var result = 1; // result: variable while (n > 1) { result *= n; n -= 1; } return result; } function factorial(n) { return (function (result) { // result: parameter while (n > 1) { result *= n; n -= 1; } return result; }(1)); }

Tennent’s Principle of Correspondence expression (function () { return expression ; }()) Except this arguments var function break continue return Any expression or statement can be wrapped in an immediately invoked function without changing meaning…

Closure Lexical Scoping Static Scoping Functions can nest. Functions are values.

Closure The context of an inner function includes the scope of the outer function. An inner function enjoys that context even after the parent functions have returned. Function scope works like block scope.

Block Scope { let a; { let b; … a … … b … } … a … }

Function Scope function green() { let a; function yellow() { let b; … a … … b … } … a … }

Function Scope function green() { let a; function yellow() { let b; … a … … b … } … a … } a

Function Scope function green() { let a; function yellow() { let b; … a … … b … } … a … } a b

Lisp [1958] dynamic scope nested functions function values Algol 60 [1960] lexical scope nested functions functions are not values C [1972] lexical scope functions cannot nest functions are values

Inner survives the outer function green() { let a; return function yellow() { let b; … a … … b … } … a … }

Global var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var digit_name = function (n) { return names[n]; }; alert(digit_name(3)); // 'three'

Slow var digit_name = function (n) { var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; return names[n]; }; alert(digit_name(3)); // 'three'

Closure var digit_name = (function () { var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; return function (n) { return names[n]; }; }()); alert(digit_name(3)); // 'three'

Start Over var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var digit_name = function (n) { return names[n]; }; alert(digit_name(3)); // 'three'

Immediate function returns a function var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var digit_name = (function () { return function (n) { return names[n]; }; }()); alert(digit_name(3)); // 'three'

Closure var digit_name = (function () { var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; return function (n) { return names[n]; }; }()); alert(digit_name(3)); // 'three'

function fade(id) { var dom = document.getElementById(id), level = 1; function step() { var h = level.toString(16); dom.style.backgroundColor = '#FFFF' + h + h; if (level < 15) { level += 1; setTimeout(step, 100); } setTimeout(step, 100); }

new prefix operator Function.prototype.new = function new() { var that = Object.create(this.prototype), result = this.apply(that, arguments); return (typeof result === 'object' && result) || that; };

Pseudoclassical function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; };

prototype id string function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; constructor toString function prototype constructor toString function new Gizmo( string ) Gizmo Object

prototype id string function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; constructor toString function prototype constructor toString function new Gizmo( string ) Gizmo Object

function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; prototype id string constructor toString function prototype constructor toString function new Gizmo( string ) Gizmo Object

Pseudoclassical Inheritance If we replace the original prototype object, then we can inherit another object's stuff.

function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; };

prototype function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; test function constructor toString function id string new Hoozit( string ) Hoozit Gizmo

prototype function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; test function constructor toString function id string new Hoozit( string ) Hoozit Gizmo

Pseudoclassical Inheritance function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; };

Prototypal Inheritance var gizmo = new_constructor(Object, function (id) { this.id = id; }, { toString: function () { return "gizmo " + this.id; } }); var hoozit = new_constructor(gizmo, function (id) { this.id = id; }, { test: function (id) { return this.id === id; } });

function new_constructor(initializer, methods, extend) { var prototype = Object.create(typeof extend === 'function' ? extend.prototype : extend); if (methods) { methods.keys().forEach(function (key) { prototype[key] = methods[key]; }); } function constructor() { var that = Object.create(prototype); if (typeof initializer === 'function') { initializer.apply(that, arguments); } return that; } constructor.prototype = prototype; prototype.constructor = constructor; return constructor; }

Function as module var … function … (function () { var … function … }());

A Module Pattern var singleton = (function () { var privateVariable; function privateFunction(x) {...privateVariable... } return { firstMethod: function (a, b) {...privateVariable... }, secondMethod: function (c) {...privateFunction()... } }; }());

A Module Pattern (function () { var privateVariable; function privateFunction(x) {...privateVariable... } GLOBAL.methodical = { firstMethod: function (a, b) {...privateVariable... }, secondMethod: function (c) {...privateFunction()... } }; }());

Module pattern is easily transformed into a powerful constructor pattern.

Power Constructors 1.Make an object. Object literal new Object.create call another power constructor

Power Constructors 1.Make an object. Object literal, new, Object.create, call another power constructor 2.Define some variables and functions. These become private members.

Power Constructors 1.Make an object. Object literal, new, Object.create, call another power constructor 2.Define some variables and functions. These become private members. 3.Augment the object with privileged methods.

Power Constructors 1.Make an object. Object literal, new, Object.create, call another power constructor 2.Define some variables and functions. These become private members. 3.Augment the object with privileged methods. 4.Return the object.

Step One function constructor(spec) { var that = otherMaker(spec); }

Step Two function constructor(spec) { var that = otherMaker(spec), member; }

Step Three function constructor(spec) { var that = otherMaker(spec), member, method = function () { // spec, member, method }; that.method = method; }

Step Four function constructor(spec) { var that = otherMaker(spec), member, method = function () { // spec, member, method }; that.method = method; return that; }

Pseudoclassical Inheritance function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; };

Functional Inheritance function gizmo(id) { return { id: id, toString: function () { return "gizmo " + this.id; } }; } function hoozit(id) { var that = gizmo(id); that.test = function (testid) { return testid === this.id; }; return that; }

Privacy function gizmo(id) { return { toString: function () { return "gizmo " + id; } }; } function hoozit(id) { var that = gizmo(id); that.test = function (testid) { return testid === id; }; return that; }

function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; function hoozit(id) { var that = gizmo(id); that.test = function (testid) { return testid === id; }; return that; } var my_hoozit = new Hoozit("success"), test = my_hoozit.test; alert(test("success")); // B O O M !

function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; function hoozit(id) { var that = gizmo(id); that.test = function (testid) { return testid === id; }; return that; } var my_hoozit = hoozit("success"), test = my_hoozit.test; alert(test("success")); // true

JavaScript has good parts.

Later: Episode IV The Metamorphosis of Ajax