More on JavaScript classes, function warzone

Just like Python, JavaScript tends to create things once you mention them and they don’t yet exist. In my opinion, that’s a bit more harmful than useful, because there’s danger in accidentally creating new variables and values when you assumed it would be already holding a known value. Coming from a C/C++/Java background, I would expect some kind of error for the operation:

<html>
<body onload="testFunction()">
<div id="content"></div>

<script>
function testFunction() {
    function Test() {
        var somevar=1;
    };

    var test = new Test();
    test.somevar += 10;

    document.getElementById("content").innerHTML = ""+test.somevar;
}
</script>
</body>
</html>

In this context, somevar might not exist yet, and still, you’re adding 10 to its value! By printing it is possible to check that this var is a NaN, and no errors are issued. To properly (as I eventually found out by trying) get and set its value, one must create getter and setter functions, to “publicly interface” in other contexts:

<html>
<body onload="testFunction()">
<div id="content"></div>

<script>
function testFunction() {
    function Test() {
        var somevar=1;

        this.getSomevar = function() {
            return somevar;
        };

        this.setSomevar = function(value) {
            somevar = value;
        };
    };

    var test = new Test();
    test.setSomevar(test.getSomevar() + 10);

    document.getElementById("content").innerHTML = ""+test.getSomevar();
}
</script>
</body>
</html>

But hey, be careful when using “this”, its context is related to the current function, not the “class”, as one would think coming from a Java mindset. Using “this” inside class functions can cause undesired effects, such as defining new variables inside the “method” context and again we’ll run into the NaN problem:

<html>
<body onload="testFunction()">
<div id="content"></div>

<script>
function testFunction() {
    function Test() {
        var somevar=1;

        this.getSomevar = function() {
            return this.somevar;
        };

        this.setSomevar = function(value) {
            this.somevar = value;
        };
    };

    var test = new Test();
    test.setSomevar(test.getSomevar() + 10);

    document.getElementById("content").innerHTML = ""+test.getSomevar();
}
</script>
</body>
</html>

Pushed some updates to the game on github. 🙂

Advertisement

Comment this

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s