Scoping and Hoisting
JavaScript variables have one of two
scopes:
Global scope
Local scope within a function
JavaScript does not support block scope
If you declare a variable inside a block, it is
hoisted
var num
= 7; to function scope
function demonstrateScopingAndHoisting() {
if (true) {
var num = 42;
}
alert("The value of num is " + num);
// Displays 42, not 7.
}
Singleton Objects and Global Functions in
JavaScript
JavaScript defines several singleton objects,
such as:
Math
JSON
JavaScript also defines global functions,
such as:
parseInt()
parseFloat()
isNan()
Creating Simple Objects
There are several ways to create new
objects in JavaScript:
var employee1 = new Object();
var employee2 = {};
You can define properties and methods on
an object:
var employee1 = {};
[Link] = "John Smith";
[Link] = 21;
[Link] = 10000;
[Link] = function(amount) {
// Inside a method, "this" means the current object.
[Link] += amount;
return [Link];
}
Using Object Literal Notation
Object literal notation provides a shorthand
way to create new objects and assign
properties and methods:
var employee2 = {
name: "Mary Jones",
age: 42,
salary: 20000,
payRise: function(amount) {
[Link] += amount;
return [Link];
},
displayDetails: function() {
alert([Link] + " is " + [Link] + " and earns " + [Link]);
}
};
Using Constructors
Constructor functions define the shape of
objects
They create and assign properties for the target
object
var Account = function (id, name) {
[Link]
id;
The =
target
object is referenced by the this
[Link]
= name;
keyword
[Link] = 0;
[Link] = 0;
};
acc1 = new Account(1, "John");
var
Use
constructor
function to create new
var acc2the
= new
Account(2, "Mary");
objects with the specified properties:
Using Prototypes
All objects created by using a constructor
function have their own copy of the
properties defined by the constructor
All JavaScript objects, including constructors,
have a special property named prototype
Use the prototype to share function definitions
between objects:
[Link] = {
deposit: function(amount) {
[Link] += amount;
[Link]++;
},
// Plus other methods
};