Javascript Scope Testing

Test 1: Basic Scope

Code:

var a = "This is a";

function scope1() {
	var b = "This is b";
	
	// Print a
	document.writeln(a);
	// Print b
	document.writeln(b);
}

// Run the function
scope1();

Run:

Test 2: Global vs Local Scope

Code:

var a = "Global";

function scope1() {
	var a = "Local";
	
	// Print Global
	document.writeln(this.a);
	// Print Local
	document.writeln(a);
}

// Run the function
scope1();

Run:

Test 3: Object Scope

First, if you haven't read up on JavaScript objects, you probably should.

Code:

// Create a new Object
var a = new Object();
// Assign a public variable
a.public = "Public";

// Print the public variable
document.writeln(a.public);
// Show static variable is not set (outputs undefined)
document.writeln(a.static);

// Assign a static variable to all objects of type Object using the keyword prototype
Object.prototype.static = "Static";

// Assign a nonstatic variable to a type of object
Object.nonStatic = "Non-Static";

// Print the static variable using Object a
document.writeln(a.static);
// Show nonstatic variable did not get assigned (outputs undefined)
document.writeln(a.nonStatic);
// Print the nonstatic variable from the generic Object
document.writeln(Object.nonStatic);

Run:

Test 4: Custom Object Scope

Again, if you haven't read up on JavaScript objects, you probably should.

Code:

// Define a custom object
function b() {
	// Declare public variable
	this.public = "B Public";
	// Declare protected variable
	var nonPublic = "B Protected";
	
	// Declare public function
	this.protectedAccess = function () {
		return nonPublic;
	};
}

// Create a new instance of the object type b
var bHold = new b();
// Print public variable
document.writeln(bHold.public);
// Print protected variable (will print undefined)
document.writeln(bHold.nonPublic);
// Print protected variable via function
document.writeln(bHold.protectedAccess());

Run:

Test 5: this

Code:

HTML

<input type="button"  value="Print Button"  name="The Button"  id="test5Button" /><input  type="button"  value="Print Object"  id="test5Obj" />

Javascript

function button() {
	// Set the Objects Name
	this.name = "The Object";
	
	// Get the pre area to attach the results to
	var pre = document.getElementById('pre5');
	
	// Get the Print Button Button
	var button = document.getElementById('test5Button');
	// Set the onclick handle
	button.onclick = function (event) {
		// Print The Button
		pre.innerHTML = this.name;
		// Prevent submit in some browsers
		event.preventDefault();
	};
	
	// Get the Print Object Button
	var obj = document.getElementById('test5Obj');
	// A Self Reference to have access to this object
	var SelfReference = this;
	obj.onclick = function (event) {
		// Print The Object
		pre.innerHTML = SelfReference.name;
		event.preventDefault();
	}
}
// Create a new instance of the button to initialize the above
var b = new button();

Run: