JMU
ECMAScript/JavaScript
An Introduction for Programmers


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Characters and White Space
Identifiers
Comments
Primitive Types
Variables
Assignment Operator
Arithmetic Operators
Relational Operators
Relational Operators (cont.)
Relational Operators (cont.)
Logical Operators
The if Statement
while Loops
do-while Loops
for Loops
Objects
Creating Specialized Objects
The Membership Operator
The Membership Operator (cont.)
Existence of Properties
for in Loops
Arrays
Operating on Arrays
The Length of an Array
for of Loops
Arrays of Arrays
Relational Operators Revisited
Values and References
Type Passed By Compared By
boolean Value Value
number Value Value
Object Reference Reference
string Immutable Value
Functions
Defining Named Functions
Defining Anonymous Functions
Invoking/Executing
Variable Scope
A More Sophisticated Understanding of Scope
Functions as Data
function area(width, height)
{
    return width*height;
}

var f = area;

Note: This is very different from, for example, var size = area(3,5); which executes area. f is the same function as area and can be used the same way.

Immediately-Invoked Function Expressions (IIFEs)
Methods
Methods (cont.)
// Assign an object literal to a variable
var r = {
            width: 10;
            height: 5;

            area: function()
                  {
                      return this.width * this.height;
                  }
        }

// Use the object
var a = r.area();
What is this?
Classes and Objects in some Object-Oriented Languages
Pseudoclasses in ECMAScript/JavaScript
A Rectangle Pseudoclass
function Rectangle(width, height)
{
    this.width  = width;
    this.height = height;

    this.area   = function()
                  {
                      return this.width * this.height;
                  }
}
Thinking About this Approach
Prototypes
An Improved Rectangle Pseudoclass
// The Constructor
function Rectangle(width, height)
{
    this.width  = width;
    this.height = height;
}


// The area() Method
Rectangle.prototype.area = function()
                           {
                               return this.width * this.height;
                           }
Owned Properties
Wrappers