打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
? JavaScript++: JavaScript Classes, Modules, Type Safety & More

 

JavaScript++ provides the same familiar C-style language syntax of JavaScript and brings modern language features such as classes;
block scoping and constants; pluggable type systems and type safety; packages and modules; comprehensive standard libraries; enhanced
regular expressions and PCRE; and more to JavaScript with almost no learning curve through an extended ES3 grammar.

As JavaScript grows and extends its reach beyond the web browser, and larger applications with increasing complexity begin to pop up, the original JavaScript syntax - which was designed for adding small programs and interactivity to web pages - needs to be extended to facilitate development of increasingly complex web applications. With features such as classes, static typing, and a package/module system, JavaScript++ enables large-scale software development that is maintainable, reliable, and economical.

JavaScript++ compiles to ES3-compatible JavaScript and is compatible with IE 5.5 and all versions of Firefox, Chrome, and the vast majority of web browsers dating back to 1999 for the client-side and Node.js, v8, SpiderMonkey, and Rhino on the server-side. Furthermore, JavaScript++ is backwards-compatible with all existing JavaScript code and libraries (jQuery, YUI et al), and JavaScript++ code can seamlessly and easily be embedded into your existing JavaScript code.

The JavaScript++ compiler supports regular JavaScript so there is practically no learning curve. Just pick and choose which JavaScript++ features you want to incorporate and learn on demand. Here's a 30 minute JavaScript++ tutorial for programmers which assumes an understanding of computer science fundamentals, class-based OOP, and JavaScript.

JavaScript++ incorporates features from Python, Perl, Java/C#, ES4, Harmony, Haskell, and more while incorporating its own unique features. The driving philosophy behind JavaScript++ is productivity, and it will make everything from small scripts to large applications easier and faster to write. Take the mundane out of your JavaScript code with JavaScript++!

Overview

  1. Classes
  2. Block Scope
  3. Pluggable Type Systems and Type Safety
  4. Standard Library and Modules System
  5. Regular Expressions and PCRE.js
  6. Functional Programming
  7. Array Programming: Scoped Extensions, Comprehensions, and More
  8. ... And Lots More!

Click Here to Download JavaScript++

Classes

JavaScript++ implements the Java/C# flavor of class-based object-oriented programming (OOP). JavaScript++ is multi-paradigm and classes co-exist with regular JavaScript language features; out of the box, JavaScript++ supports functional programming, prototypal inheritance, and class-based inheritance. JavaScript++ expands class-based OOP further by taking advantage of the expressive power of vanilla JavaScript to implement concise singleton patterns, concise anonymous classes, and classes as first-class citizens.

The following table provides a visualization of JavaScript++ versus Java/C# and libraries that emulate class-based inheritance in JavaScript:


JavaC#JavaScript++Prototype.jsMooTools
ClassesYesYesYesPartialPartial
Nested ClassesYesYesYesNoNo
SubclassesYesYesYesYesYes
Access ModifiersYesYesYesNoNo
  PrivateYesYesYesPartialPartial
  PublicYesYesYesYesYes
  ProtectedYesYesYesNoNo
PolymorphismYesYesYesYesYes
SuperYesYesYesYesYes
ConstructorsYesYesYesYesYes
DestructorsNoYes (?)Yes (?)NoNo
Instance MembersYesYesYesYesYes
Static MembersYesYesYesYesYes
Overloadable MethodsYesYesYesPartial (?)Partial (?)
SingletonsYesYesYesYesYes
Anonymous ClassesYesYesYesNoNo
Class ClosuresNoNoYesNoNo
Class DeclarationsYesYesYesYesYes
Class ExpressionsNoNoYesYesYes
First-class CitizensNoNoYesYesYes

If the table isn't enough for you, here's a side-by-side comparison of JavaScript++ and C# code:

class Foo {
    protected var findMe = 100;
}
class Bar extends Foo {
    class Baz extends Foo {
        public function Constructor() {
            console.log("Baz: " + findMe);
        }
    }

    public function Constructor() {
        findMe = 5;
        console.log("Bar: " + findMe);
        new Baz();
    }
}

new Bar();




class Foo {
    protected int findMe = 100;
}
class Bar : Foo {
    class Baz : Foo {
        public Baz() {
            System.Console.WriteLine("Baz: " + findMe);
        }
    }

    public Bar() {
        findMe = 5;
        System.Console.WriteLine("Bar: " + findMe);
        new Baz();
    }
}
class MainClass {
    public static void Main (string[] args) {
        Bar bar = new Bar();
    }
}

The output of both the JavaScript++ and C# code are identical, and the snippets themselves look very similar.

It's worth noting classes in JavaScript++ are significantly easier and more intuitive than the emulation of classes through a regular JavaScript library. For example, there are no "special" patterns to learn to differentiate static and instance variables, and someone reading your code can instantly distinguish the two. With JavaScript++, you can practically take Java/C# classes from the net and translate it 1:1 to JavaScript++ by changing the int's to var's and using the equivalent libraries/functions.

Unlike Java, JavaScript++ does not force you to write classes for everything and you're still allowed to use the classic functional programming paradigms and prototypal inheritance you know from regular JavaScript. When you do need classes, JavaScript++ treats classes as first-class citizens:

function foo(myClass) {
    return new myClass;
}

class Bar {
    protected var widget = Math.random();
}

foo(new class { //Pass an anonymous singleton to avoid excessive instantiation due to 'baz' being nested
    public function Constructor() {
        return class Baz extends Bar {
            public function Constructor() { return [ widget ] }
        }
    }
})

Classes constructed with Javascript++ can export directly to regular Javascript meaning you can write your libraries and classes using Javascript++, and when regular Javascript users use your class, it's as simple as:

var myInstance = new myClass(foo, bar, baz);

Better yet: all of your access modifiers, subclasses, nested classes, and so on will be retained and degrade gracefully. Public properties remain public, private methods remain private, static properties work as expected (likewise, instance variables work only for actual instances), overloaded methods and constructors are still overloaded, and nested classes and inherited classes can still only access the superclass's protected and public properties.

Finally, importing your classes into regular Javascript is a cinch. No library or external dependencies are required. Working with Javascript++ classes in regular Javascript almost feels like classes were natively implemented in Javascript!

Back to Top :: Download JavaScript++ Now

Block Scope

Unlike previous attempts to implement block scope into JavaScript, JavaScript++ does not use try/catch hacks (e.g. what Google does, but it was originally discovered by Opera) or functions; both these methods are too slow and clunky for practical usage. Instead, JavaScript++ creates temporary variables that get explicitly tagged for garbage collection by the end of the block. This provides almost zero performance hit as even "real" block scoped variables are simply a variable declaration.

JavaScript++ even handles closures and other tricky concepts just fine. For example, here's block scope combined with closures:

function myClosure(x) {
    let foo = +x || 0;
    
    {
        let foo = 1;
    }
    
    return function(y) {
        return +y + foo
    }
}

myClosure(500)(100) //600
function myClosure(x) {
    var _bScope26 = {};
    _bScope26.a = +x || 0;
    
    {
        var _bScope22 = {};
        _bScope22.b = 1;
        _bScope22 = null;
    }
    
    return function(y) {
        var _bScope24 = {};
        
        return +y + _bScope26.a
    }
}

myClosure(500)(100) //600

Back to Top :: Download JavaScript++ Now

Pluggable Type Systems and Type Safety

JavaScript++ integrates "pluggable type systems" based on the theories of Gilad Bracha.

Type theory is a loaded topic, and it's difficult to satifsy everyone: some want strong typing, some want optional typing, some want type inference, and the list goes on. One size does not fit all in web development. A "pluggable" type system allows you to create (or download) your own type system and "plug" it into the compiler.

By default, JavaScript++ uses the same dynamic and weak typing system you're familiar with in regular JavaScript so types are completely optional. However, you can easily import your own type systems and rules. JavaScript++ ships with a standard strong, static typing system called "strict," and importing and using it is as easy as:

#typesys strict //Preprocessor directive to tell the compiler which type system to use

var foo as String = "foo";

var bar as Number = foo; //Error, type mismatch

var baz = 1; //Error, no type declaration

As you may have observed, we've chosen to not incorporate the non-standard ES4 syntax as seen in AS3. We've determined that pressing shift and reaching for the colon (e.g. var a:String = "foo";) was too cumbersome and harder to type. Since variable declarations happen almost all the time, we chose not to inhibit efficiency. Furthermore, with pluggable type systems, we can do away with type declarations altogether in the future with a type inference system.

Yes, there is a preprocessor, but we promise it's nothing like the C preprocessor where your code becomes riddled with preprocessor directives. There are a few features in JavaScript++ which requires us manipulate compiler behavior beforehand. JavaScript++ preprocessor directives can only exist at the top of your code so you don't have to hunt them down.

For advanced users: the type system plugins are written in regular JavaScript, and you have full access to the AST nodes and type annotations so you can create an optional typing system, a type inference system, and so on. Writing your own type system can be as simple as a single function: the function is automatically called by the core compiler when it determines type checking is necessary; you won't need to write logic to "filter" out certain AST nodes or extraneous code; this makes creating your own type system extremely intuitive and simple.

Back to Top :: Download JavaScript++ Now

Standard Library and Modules System

JavaScript++ ships with a set of standard libraries, and it's easy to create your own modules. The JavaScript++ compiler will resolve dependencies, and you have your choice of static vs dynamic linking, lazy loading, and so on.

Need a standard cryptography library? Check. Writing a quick, small script using DOM document.getElementsByClassName and don't want to search for a compatibility snippet every time? Check. Need backwards compatibility for the newly-standardized Array.prototype.map, Array.prototype.filter, String.prototype.trim, etc.? Check. Are you just plain tired of searching for scripts and snippets to do what you take for granted in other languages or having to resolve library incompatibilities? Check; JavaScript++ has you completely covered.

Our goal is to build a universal standard library for the JavaScript community that's compatible with JavaScript++, regular JavaScript, CoffeeScript, server-side JavaScript, and so on. It'll come complete with type annotations, overloaded functions, and everything you'd expect from a full-featured standard library so IDE makers can implement all the fantastic features they've been wanting to implement, and languages such as JavaScript and CoffeeScript don't need to sacrifice their lightweight and expressive syntax but will have a standard library that can rival Python's and .NET's.

JavaScript++ will be backwards-compatible with CommonJS.

Back to Top :: Download JavaScript++ Now

Regular Expressions and PCRE.js

Javascript++ gives you regular expressions on steroids.

JavaScript++ provides full PCRE-compatible regular expression patterns - everything from lookbehinds to possessive quantifiers. There are no hacks or tricks; we wrote PCRE.js from scratch as part of the CompiledJS project - which includes JavaScript++. Best of all, there's no need for excessive escaping as all PCRE-compatible regular expression patterns will be compatible with the classic JS regular expression literals, and we take care to automatically use the native regex parser where PCRE is not used.

Speaking of excessive escaping, this is the web. We often work with URL's and the like, and Javascript++ takes note of this with features such as custom regular expression delimiters:

//Declare a custom regex delimiter by prefixing the regex with "m"
var url = m@https?://developer\.mozilla\.org/en/SpiderMonkey@i.test("foobar");
//Compiled to JavaScript
var url = /https?:\/\/developer\.mozilla\.org\/en\/SpiderMonkey/i.test("foobar");

JavaScript++ also supports multi-line regular expression patterns, comments, free spacing mode (ignores comments and whitespace), implicit RegExp.prototype.exec as implemented in SpiderMonkey and v8, and more.

Back to Top :: Download JavaScript++ Now

Functional Programming

JavaScript++ incorporates all your favorite features from JavaScript which enable functional programming: first-class functions, anonymous functions, closures, and higher order functions. JavaScript++ extends these features and aims for conciseness. To this end, JavaScript++ introduces features such as default function parameters to make your life easier:

function add(a = 1, b = 1) {
    return a + b
}

add(3) //4
  • Default parameters for functions
  • A shorter way to access arguments: the args array - which is always an array and not an "array-like object"
  • Easier, more readable function overloading. The same function overloading syntax you know from C++, Java, and C# is available in JavaScript++
  • Expression closures a la JavaScript 1.8: function add(x = 0, y = 0) return x + y;
  • JavaScript++ comes equipped with all the ES5 higher-order array methods such as map and filter in its standard libraries so you can use them on any browser or host environment
  • Rest parameters
  • Scoped object extensions - Extend the prototypes of native global objects inside your function/namespace only

Back to Top :: Download JavaScript++ Now

Array Programming: Scoped Extensions, Comprehensions, and More

Perhaps even less known than functional programming is the "array programming" paradigm. The core idea is to simplify operations on similar data, and consequently, we can express larger concepts and code more concisely. You've probably already been done array programming without even realizing it!

JavaScript's unique mixture of prototypal inheritance and functional programming paradigms can enable interesting new approaches in array programming...with the proper extensions.

Prototypal inheritance is great and allows for amazing expressiveness -- until you start polluting the prototypes of the native global objects or avoid extending these objects altogether for fear of conflicts with libraries or future code. JavaScript++ incorporates the Harmony proposal of "scoped object extensions" where you can extend the prototypes of native global objects (or any object) while keeping these extensions within the scope of the nearest function or namespace. Now you can start taking full advantage of prototypal inheritance in a way you've always wanted to without holding back for fear of conflicts or otherwise.

JavaScript++ also throws in array comprehensions, ranges, destructuring assignments, array operators, and even more array extensions via the Standard Library.

import jspp.lang;

(function() {
    //Extend Array.prototype - but keep it in this scope
    extension Array.prototype {
        //Split first and last x elements
        analyze: function(x as Number) {
            return { original: this, split: this.slice(x, -x) };
        }
    }
    
    while (true) {
        //Create an array of arbitrary length and fill it with an array comprehension
        var x = [i for (let i inside Array(+readline() || 0)];
        
        x.analyze(1); //Calls Array.prototype.analyze - which is scoped
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
各大互联网公司2014前端笔试面试题–JavaScript篇 – 码农网
深入浅出妙用 Javascript 中 apply、call、bind
JavaScript 原型中的哲学思想
45个实用的JavaScript技巧、窍门和最佳实践 | Sina App Engine Blog
Overview of the Prototype Javascript Library
Extending JavaScript Objects and Classes
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服