Ben Nadel: Dereferencing Javascript Variables

click scope test

by nickadeemus2002

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<div id="content"></div>

JavaScript

function TestClass(strName) {
    this.Name = strName;
}
TestClass.prototype.AlertValue = function (anyValue) {
    console.log(this.Name + " is alerting: " + anyValue);
}

function Init() {
    var objContentDiv = document.getElementById("content");
    var objA = null;
    var objTest = new TestClass("Tester");

    // This runs the for loop using a LOCAL scope for each iteration. 
    (function loop(intI) {
        var intX = intI;

        if (intI < 10) {

            // Create new A element.
            objA = document.createElement("a");

            // Set A display properties.
            objA.style.display = "block";
            objA.style.backgroundColor = "#F8F8F8";
            objA.style.border = "1px solid #333333";
            objA.style.padding = "10px 10px 10px 10px";
            objA.style.color = "#333333";
            objA.style.marginBottom = "15px";

            // Create text for the link.
            objA.appendChild(document.createTextNode("I should alert " + intX + " when clicked"));

            // Set the href.
            objA.setAttribute("href", "##");

            // Set the onclick method.
            objA.onclick = function () {
                objTest.AlertValue(intX)
            };

            // Attach the A to the content.
            objContentDiv.appendChild(objA);


            loop(intI + 1);
        }

    })(0);

}

$(document).ready(function(){
 Init();
});