Getting from Scripts to Applications Donald J. Sipe | Refresh Jacksonville | November 11 th 2008.

Slides:



Advertisements
Similar presentations
JavaScript: A Language of Many Contrasts
Advertisements

Intro to JavaScript. JavaScript History Client (generally browser-side) language invented at Netscape under the name LiveScript around 1995 Netscape wanted.
Written by: Dr. JJ Shepherd
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
Advanced JS The World's Most Misunderstood Programming Language ) Douglas Crockford( Shimon Dahan
Road Map Introduction to object oriented programming. Classes
VBA Modules, Functions, Variables, and Constants
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Subroutines. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We’ll just say Subroutines. –“Functions” generally means built-in.
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.
JAVASCRIPT Introduction Kenny Lam. What is Javascript?  Client-side scripting language that can manipulate elements in the DOM  Event-driven language.
CSE 190M Extra Session #5 JavaScript scope and closures slides created by Marty Stepp
Introduction to scripting
Taking JavaScript Seriously IS NOT THE WORST IDEA.
IS JAVASCRIPT OBJECT-ORIENTED? Contains objects Data Methods Doesn’t have classes Does have constructors Does have prototype functions Doesn’t provide.
Lecture 3. 2 Introduction Java is a true OO language -the underlying structure of all Java programs is classes. Everything must be encapsulated in a class.
JavaScript JavaScript is a scripting language that is most commonly used to add client- side programming to a web page. Some of the things it is used for.
Syllabus (1) WeekChapters 1Introduction to the course, basic java language programming concepts: Primitive Data Types and Operations 1, 2 2Methods, Control.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
Introduction to JavaScript Gordon Tian
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
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.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
ALBERT WAVERING BOBBY SENG. Week 4: JavaScript  Quiz  Announcements/questions.
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
10-Nov-15 Java Object Oriented Programming What is it?
Martin Kruliš by Martin Kruliš (v1.0)1.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
JavaScript, Fourth Edition
Function the Ultimate Act III. Function Method Class Constructor Module.
Julian on JavaScript: Functions Julian M Bucknall, CTO.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
COP 3813 Intro to Internet Computing Prof. Roy Levow Lecture 4 JavaScript.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
JavaScript scope and closures
1 Javascript CS , Spring What is Javascript ? Browser scripting language  Dynamic page creation  Interactive  Embedded into HTML pages.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Written by: Dr. JJ Shepherd
JavaScript for C# developers Dhananjay Microsoft MVP
21. PHP Classes To define a class, use the keyword class followed by the name and a block with the properties and method definitions Properties are declared.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Simulating OOP in JavaScript Function Constructor, Prototypes, "this" Object, Classical and Prototypal Model Software University Technical.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
JavaScript Tutorial First lecture 19/2/2016. Javascript is a dynamic computer programming language. It is lightweight and most commonly used as a part.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Modern JavaScript Develop And Design
Dr. Charles W. Kann III JavaScript Objects Dr. Charles W. Kann III
Scope, Objects, Strings, Numbers
JavaScript Syntax and Semantics
Functions BIS1523 – Lecture 17.
Chapter 9 Objects and Classes
CS5220 Advanced Topics in Web Programming JavaScript Basics
CS5220 Advanced Topics in Web Programming Node.js Basics
CSE 341 Lecture 27 JavaScript scope and closures
CS3220 Web and Internet Programming JavaScript Basics
Presentation transcript:

Getting from Scripts to Applications Donald J. Sipe | Refresh Jacksonville | November 11 th 2008

JavaScript We are here Pseudoclassical Inheritance Hello World!

JavaScript What we’ll be talking about OOP Basics Scope Closures Context Appling to OOP Constructors Methods Public Private Privileged

But First... Some handy tools Here are some handy things you might not know JavaScript can do: Object-literal notation Anonymous functions Binary assignment Dot-style and array-style access of properties

Handy Tools Object Literal Notation— Makes JSON possible // The old way var myObject = new Object(); myObject.val = “test”; // Using object literal notation var myObject = { val: “test” };

Handy Tools Object Literal Notation // The old way var myArray = new Array(1, 30, “Refresh”); // Using object literal notation var myArray = [1, 30, “Refresh”];

Handy Tools Anonymous Functions In JavaScript, functions are treated as values, which means: Functions can be assigned to variables Functions can be passed as arguments to other functions

Handy Tools Anonymous Functions // Using an anonymous function as an argument setTimeout( function () { alert( “Refresh” ); }, 1000 ); // Using a function as a variable var myFunc = function () { alert( “Refresh” ); }; setTimeout(myFunc, 1000);

Handy Tools Anonymous Functions : Building a “scope bubble” Using an anonymous function to wrap code you don’t want in the global scope var globalVar = “Refresh”; // Global scope // Create a scope bubble ( function () { var privateVar = “Jacksonville”; alert( globalVar + “ ” + privateVar ); } )(); alert (privateVar == undefined);

Handy Tools Binary Assignment Set a default value only if the variable doesn’t have a value yet // Traditional ternary assignment var myVar = myVar ? myVar : 0; // Binary assignment var myVar = myVal || 0;

Handy Tools Dot-Style and Array-Style property access var sampleObj = { color: “blue”, width: “16px” }; // Traditional dot-style access alert( sampleObj.color == “blue” ); // Alternative array-style access alert( sampleObj[“width”] == “16px” );

Scope, Closures, and Context

Scope Only functions have scope. Blocks ( if, while, for, switch ) do not. All variables are within the global scope unless they are defined within a function. All global variables actually become properties of the window object When variables are not declared using the var keyword, they decared globally.

Scope var foo = “orig”; // foo is now a global variable if ( true ) { foo = “new”; // Global foo now equals “new” } // create function to modify its own foo variable function test () { var foo = “old”; } test(); alert( foo == “new” ); // Global foo still equals “new”

Scope If you forget to use the var keyword to define a value within a function—even if it’s only used within the function—the value will be defined globally. var foo = “new”; alert( foo == “new” ); // Omitting the var keyword reverts scope // of foo to global level function badTest () { foo = “bad news”; } badTest(); // Global foo now equals “bad news” alert( foo == “bad news” );

Scope: Inner Functions Functions can be defined within one another Inner functions have access to the outer function’s variables and parameters. function getRandomInt(max) { var randNum = Math.random() * max; function ceil() { return Math.ceil(randNum); } return ceil(); // Notice that no arguments are passed } // Alert random number between 1 and 5 alert(getRandomInt(5));

Closures Inner functions maintain the scope they enjoyed when their parent function was called—even after the parent function has terminated. This allows you to effectively pass variables to functions that may not be called for some time.

Closures function delayedAlert (message, delay) { // Set an enclosed callback setTimeout( function () { // Use message variable passed to outer function alert(message); }, delay); } // Display a message with a 5 second delay delayedAlert(“Refresh”, 5000);

Context Your code will always be running within the context of another object Context is maintained through the use of the this variable. function increment() { this.x = this.x || 0; return this.x++; }; alert( increment() == 0 ); alert( increment() == 1 );

Context var myObject = { set: function (newVal) { this.val = newVal; } }; alert( myObject.val == null ); // val property not set yet myObject.set(“Refresh”); alert( myObject.val == “Refresh” ); // val equals “Refresh” // Change the context of set() to the window object window.set = myObject.set; window.set( “Refresh Jacksonville” ); alert( myObject.val == “Refresh” ); alert( window.val == “Refresh Jacksonville” );

Context: Changing Contexts JavaScript provides two handy functions for executing a function within the context of another function: call( ) apply( )

Context: Changing Contexts Using call() — Arguments passed by name // Simple function to change the color style of a node function changeColor (newColor) { this.style.color = newColor; } // window.changeColor has no style property, so call fails changeColor( “red” ); // Grab the DOM node with the id “required” var reqField = document.getElementById( “required” ); // Call changeColor() within reqField’s context changeColor.call( reqField, “red” );

Context: Changing Contexts Using apply() — Arguments passed as an array // Simple function to change the color style of a node function changeColor (newColor) { this.style.color = newColor; } // Set the text color of the body element function setBodyTextColor () { changeColor.apply( document.body, arguments ); } setBodyTextColor( “black” );

Constructors and methods

Object Oriented Programming Now let’s apply all of this information to a more classical view of OOP in JavaScript: Constructors Object Methods Public Private Privileged

About Objects Almost everything written in JavaScript is an object Objects can be though of as a collection of properties—much like a hash in other languages JavaScript doesn’t have a concept of classes like other object-oriented languages Classes are simulated using a concept called prototypal inheritance

Constructors Like other languages, JavaScript uses the new operator to create new instances of objects. // Create User object constructor function User ( name ) { this.name = name; } // Create a new instance of a User var me = new User(“Bob”); // Alert new user’s name alert( me.name == “Bob” ); // Cannot call User directly alert( User.name == undefined ); // window.name is undefined

Methods Private Privileged Public

Public Methods One way to create a public method—a function that can be freely reference by code outside your object—is to attach it to the object’s prototype. An object’s prototype is a special property that acts as a base reference of your object. This prototype object is copied and applied to all new instances of your object.

Public Methods // Our User object written a different way var User = function (name) { this.name = name; } // Add a public accessor method for name User.prototype.getName = function () { return this.name; } var me = new User( “Bob” ); alert( me.getName() == “Bob” );

Private Methods Private methods are functions that are only accessible to methods inside your object and cannot be accessed by external code.

Private Methods // Our User object with some changes var User = function (name) { this.name = name; function welcome () { alert( “Welcome back, ” + this.name + “.”); } welcome(); } // Create a new User var me = new User( “Bob” ); // Alerts: “Welcome, Bob.” // Fails because welcome is not a public method me.welcome();

“Privileged” Methods The term privileged method was coined by Douglas Crockford. It is not a formal construct, but rather a technique. Privileged methods essentially have one foot in the door: Then can access private methods and values within the object They are also publicly accessible

“Privileged” Methods // Our User object with some tweaks var User = function (name, age) { var year = (new Date()).getFullYear() – age; this.getYearBorn = function () { return year; }; }; // Create a new User var me = new User( “Bob”, 28 ); // Access privileged method to access private year value alert( me.getYearBorn() == 1980 ); // Fails because year is private alert( me.year == null );

Grand Finale Using Scope, Closures, Contexts, and what we’ve discussed about OOP, we can dynamically generate classes based on information supplied to the constructor.

Grand Finale // Our User object modified to accept an object of properties function User (properties) { // Loop through properties and create getter and setter methods for ( var i in properties ) { function () { this[“get” + i] = function () { return properties[i]; }; this[“set” + i] = function (val) { properties[i] = val; }; })(); } } // Create a new user, automatically creating get and set methods var me = new User( { name: “Bob”, age: 28 });

Grand Finale // …continued // Note that name is private within properties alert( me.name == null ); // Access privileged getname() method alert( me.getname() == “Bob” ); // Use the dynamically generated setter // to change the user’s age me.setage(21); alert( me.getage() == 21 );

References Pro JavaScript Techniques, by John Resig Douglas Crockford’s YUI Theater Presentations