CNIT 133 Interactive Web Pags – JavaScript and AJAX Advanced topic - variable.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 5: Elementary Data Types Properties of types and objects –Data objects, variables and constants –Data types –Declarations –Type checking –Assignment.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
CPSC 388 – Compiler Design and Construction
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
Road Map Introduction to object oriented programming. Classes
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Run time vs. Compile time
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
Names Variables Type Checking Strong Typing Type Compatibility 1.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
JavaScript, Fourth Edition
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Learners Support Publications Classes and Objects.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
JavaScript, Fourth Edition
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Review 1 List Data Structure List operations List Implementation Array Linked List.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Objects.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
JavaScript Variables. Definition A variable is a "container" for information you want to store. A variable's value can change during the script.
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.
Java Primer 1: Types, Classes and Operators
CNIT 133 Interactive Web Pags – JavaScript and AJAX
Modern JavaScript Develop And Design
JavaScript Fundamentals
Object Oriented Programming COP3330 / CGS5409
Classes and Objects.
Submitted By : Veenu Saini Lecturer (IT)
Classes, Objects and Methods
SPL – PS3 C++ Classes.
Presentation transcript:

CNIT 133 Interactive Web Pags – JavaScript and AJAX Advanced topic - variable

Agenda My Web Site: (download syllabus, class notes). Variable Declaration Variable Scope Primitive Types and Reference Types Garbage Collection Variables as Properties Variable Scope Revisited

Repeated and Omitted Declarations It is legal and harmless to declare a variable more than once with the var statement. If the repeated declaration has an initializer, it acts as if it were simply an assignment statement. If you attempt to read the value of an undeclared variable, JavaScript generates an error. If you assign a value to a variable that you have not declared with var, JavaScript implicitly declares that variable for you. NOTE: implicitly declared variables are always created as global variables, even if they are used within the body of a function. To prevent the creation of a global variable, you must always use the var statement within function bodies. It is best to use var for all variables, whether global or local.

Variable Scope The scope of a variable is the region of your program which it is defined. A global variable has global scope; it is defined everywhere in your JavaScript code. Variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function. Within the body of a function, a local variable takes precedence over a global variable with the same name. if you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable var scope = “global”;// declare global variable function checkscope() { var scope = “local”; // declare local variable with the same name document.write(scope);// use the local variable, not the global one } checkscope(); // prints “local”

Variable Scope (continue…) Although you can get away with not using the var statement when you write code in the global scope, you must always use var to declare local variables: scope = “global”; // declare global variable function checkscope() { scope = “local”; // change the local to global document.write(scope);// use the global myscope = “local”;// implicitly declare global variable document.write(myscope); //use new global } checkscope();//prints “locallocal” document.write(scope);//prints “local” document.write(myscope);//prints “local” Avoid implicit global variables, declare all variables with var.

No Block Scope Note that unlinke C, C++, and Java, JavaScript does not have block-level scope. All variables declared in a function, no matter where they are declared, are defined throughout the function. In the following code, the variables i,j, and k all have the same scope: all three are defined throughout the body of the function. This would not be the case if the code were written in C, C++, or Java: function test(o) { var i = 0; // i is defined throughout function if (typeof o == “object”) { var j = 0;// j is defined throughout function, not just block for(var k=0; k < 10; k++) { // k defined thru function, not just loop document.write(k); } document.write(k);// k is still defined, prints 10 } document.write(j);// j is defined, but may not be initialized }

No Block Scope (continue…) The rule that all variables declared in a function are defined throughout the function can cause surprising results: var scope = “global”; function f() { alert(scope);//displays “undefined” var scope = “local”;//variable initialized alert(scope);//display “local” } f(); The local variable is defined throughout the body of the function, which means the global variable by the same name is hidden throughout the function. Although the local variable is defined throughout, it is not actually initialized until the var statement is executed. Thus, the function f in the previous example is equivalent to the following: function f() { var scope;// local variable is declared alert(scope);// local variable exist, but still has “undefined” value scope = “local”; // lcoal variable get initialized with value alert(scope);// it has value now } NOTE: This is why it is a good programming practice to place all your variable declarations together at the start of any function.

Undefined Versus Unassigned There are two different kinds of undefined variables. The first kind of undefined variable is one that has never been declared.  An attempt to read the value of such an undeclared variable causes a runtime error. Undeclared variables are undefined because they simply do not exist.  Assigning a value to an undeclared variable does not cause an error; instead, it implicitly declares the variable in the global scope. The second kind of undefined variable is one that has been declared but has never had a value assigned to it. If you read the value of one of these variables, you obtain its default value, undefined. (this type of undefined variable might more usefully be called unassigned) var x; // declare an unassigned variable, its value is undefined alert(u);// using an undeclared variable causes an error u = 3;// assigning a value to an undeclared variable creates global var

Primitive Types and Reference Types Variables have or contain values. But just what is it that they contain?  Primitive types: Numbers, boolean values, and the null and undefined types.  Reference types: objects, arrays, and functions types.  Whether strings are a primitive or reference type is actually moot (debatable). (other book said strings are reference types) A primitive type has a fixed size in memory. (number occupies eight bytes, a boolean value with only one bit) Reference types are another matter: Objects, arrays, and functions do not have a fixed size, their values cannot be stored directly in the eight bytes of memory associated with each variable. Instead, the variable stores a reference to the value. This reference is some form of pointer or memory address. It is not the data value itself, but it tells the variable where to look to find the value.

Primitive Types and Reference Types (continue…) Primitive and reference types behave differently: var a = 3.14;//declare and initialize a var var b = a;//copy the var value to a new var a = 4;//modify the value of the original var alert(b);//display 3.14 Reference types: var a = [1,2,3]; //initialize a var to refer to an array var b = a; //copy that reference into a new var a[0] = 99; //modify the array using the original reference alert(b); //display the changed array [99,2,3]

Garbage Collection Since strings, objects, and arrays do not have a fixed size, storage for them must be allocated dynamically, when the size is known. Every time a JavaScript program creates a string, array, or object, the interpreter must allocate memory to store that entity, those memory must eventually be freed up for reuse, or the JavaScript will use up all the available memory on the system an crash. JavaScript relies on a technique called Garbage Collection. The JavaScript interpreter can detect when an object is no longer needed and its memory can be reclaimed: var s = “hello”;//allocate memory for a string var u = s.toUpperCase(); //create a new string s = u;//overwrite reference to original string After this code runs, the original string “hello” is no longer reachable; there are no reference to it in any variables in the program. the system detects this fact and frees up its storage space for reuse. Garbage collection is automatic and is invisible to the programmer.

Variables as Properties There are a lot of similarities in JavaScript between variables and the properties of objects. They are both assigned the same way, they are used the same way in JavaScript expressions. Variables in JavaScript are fundamentally the same as object properties.

The Global Object When the JavaScript interpreter starts up, one of the first things it does, before executing any JavaScript code, is create a global object. The properties of this object are the global variables of JavaScript programs. When you declare a global JavaScript variable, you are actually defining a property of the global object. The JavaScript interpreter initializes the global object with a number of properties that refer to predefined values and functions (e.g. Infinity, parseInt, and Math properties refer to the number infinity, the predefined parseInt() function, and the predefined Math object) In top-level code (JavaScript code that is not part of a function), you can use the JavaScript keyword this to refer to the global object. (within functions, this has a different use) In Client-side JavaScript, the Window object serves as the global object for all JavaScript code contained in the browser window it represents.

Local Variables: The Call Object Local variables are properties of the call object. The call object has a shorter lifespan than the global object, but it serves the same purpose. While the body of a function is executing, the function arguments and local variables are stored as properties of this call object. The use of an entirely separate object for local variables is what allows JavaScript to keep local variables from overwriting the value of global variables with the same name.

JavaScript Execution Contexts Each time the JavaScript interpreter begins to execute a function, it creates a new execution context for that function. An execution context is in which any piece of JavaScript code executes. JavaScript code that is not part of any function runs in an execution context that uses the global object for variable definitions. And every JavaScript function runs in its own unique execution context with its own call object in which local variables are defined. JavaScript allows multiple global execution contexts, each with a different global object. (e.g. Client-side JavaScript in which each separate browser window, or each frame within a window, defines a separate global execution context.) Client-side JavaScript code in each frame or window runs in its own execution context and has its own global object. However, these separate client-side global objects have properties that link them. Thus, JavaScript code in one frame might refer to another frame with the expression parent.frames[1], or parent.frames[1].x refers to global variable x in frame two.

Variable Scope Revisited Every JavaScript execution context has a scope chain associated with it. This scope chain is a list or chain of objects. When JavaScript code needs to look up the value of a variable x (a process called variable name resolution), it starts by looking at the first object in the chain. If that object has a property named x, the value of that property is used. If the first object does not have a property named x, JavaScript continues to the next object, and so on.