infinnie / infinnie.github.io

https://infinnie.github.io/
Apache License 2.0
0 stars 1 forks source link

If I were to design the JavaScript block scope… #13

Open infinnie opened 6 years ago

infinnie commented 6 years ago

Continuing #7.

Proper block scope rules, in my own opinion, should be something like:

block {
    var a = 2333; // block scope now.
}
a // error thrown!

In if’s and for-loops, I suggest it be optionally inserted into one of the two places—or both:

if (condition) block {
    // do something
}

Or

block for (var t = 1; t < 233; t++) {
    things[t] = function () {
        alert(t); // although t is block scoped, 233 is always alerted
    };
}

Or with block arguments:

block for (var t = 1; t < 233; t++) block(t) {
    var x = 1; // block scope
    things[t] = function () {
        alert(t); // 1 to 232
    };
}

Use other names in parameters:

block($ = jQuery) {
    // As if it were your good old IIFE
}

Lexical this:

(function () {
    block {
        console.log(this.a); // 1
    }
}).call({a: 1});

Finally it supports implicit return:

var a = block {
    1;
    2;
};

a // 2