[Coffeescript] Writing JavaScript code in a graceful way

Source: Internet
Author: User

??

I have been programming JavaScript for many years, write a lot of JS code, even if it is my experience, but I still work hard to write more beautiful JS code, in this article, I will explore why writing beautiful JS code is so difficult, How to improve it with Coffescript (a simple language that compiles to JS).

What is graceful code?

I want to state from a personal point of view how to define graceful code

    • 1, beautiful code is to use less code to solve the problem;
    • 2, beautiful code is readable and easy to understand
    • 3, beautiful code is a piece of nothing can be added or nothing superfluous can be removed code (like great design)
    • 4, the shortest length is another aspect of graceful code, not as a goal or a trade-off

So for me, the beautiful code is the least-coded, available, easy-to-read composite effect.

An example of a graceful JavaScript code:

With Fibonacci functions , for example, this function should be known to most programmers. There is not a pretty implementation here, because the code lacks structure and uses a lot of unnecessary verbose code:

1234567891011 function f (n) { Code class= "javascript keyword" >var s= 0; if (n = = 0) return (s); if (n = = 1) { s + = 1; return (s); " else { return (f (n-1) + f (n-2));     } }

Here's another version of the implementation, and I've found more elegance and grace, especially if you're familiar with single-line if else (trinocular conditional operations):

12 functionfib(n) {    returnn<2 ? n : fib(n-1) + fib(n-2)}

The same beautiful piece of code, the number of lines in the line is not necessarily so important

1234 functionfib(n) {    if (n < 2)        return n    returnfib(n-2) + fib(n-1)}

The problem with javascript:

I think one of the main problems with JavaScript is its confusing mix of different languages: JavaScript is a functional language, JavaScript is an object-oriented language, but it's a prototype-based JavaScript is dynamic very close to Lisp rather than C/java, but the name of C/java syntax JavaScript is confusing, but with Java there is no relation to the language has a characteristic crisis, programmers try to impose paradigm into JavaScript, But that's not a good idea, because JavaScript is not Java, not sheme, or python, like any other language has its strengths and weaknesses.

At the same time, JavaScript's sloppy design and poor decision-making are manifested in this, the dynamic domain like this, the syntax for inheritance, and the difficulty of fixing these issues due to backward compatibility considerations. Here is a good quote from the creator of JavaScript, the bright spot in the environment where JavaScript was born: "JavaScript sounds like Java, that's all, like a dumb little brother in Java, But I had to finish in 10 days or something worse than JavaScript would happen "-brendan Eich

Coffeescript: A new way to write better JavaScript

Coffeescript is a refined language that can be compiled into JavaScript. Its purpose is to reveal the excellent parts of JavaScript in a simple way.

Coffeescript won't end your JavaScript code.

One of the reasons I like Coffeescript is that it compiles to JavaScript, which means I can reuse all of my current JavaScript code, and I don't need to rewrite any code to Coffeescript, which is a great deal, especially because our wedoist The JavaScript codebase is huge and it takes months to rewrite it into another language. Coffeescript is also a mini-JavaScript, like the improved JavaScript version, and the bad ones are replaced. At the same time its syntax is changed from C/java language to Ruby or Python (great because JavaScript is closer to Ruby, Python than C or Java).

How Coffeescript is compiled into JavaScript

To illustrate the compilation, let's give an example to see how he works. Coffeescript Code:

12 square = (x) -> x * xcube   = (x) -> square(x) * x

Compile into JavaScript code:

1234567 var cube, Square; square = function (x) { &NBSP;&NBSP; return x * x; cube = function (x) { &NBSP;&NBSP; return square (x) * x;

As you can see from the example above, the mapping of Coffeescript and javascirpt is very straightforward. On another site you can find many examples of how coffeescript compiled into JavaScript.

Coffeescript: overriding example

In order to give you a sense of coffeescript, here is a small JavaScript example, I will re-write Coffeescript.

1234567891011121314151617 get: function(offset, callback, limit) {    var self = this;    var data = {        project_id: Projects.getCurrent().id,        limit: limit || this.default_limit    }    if(offset)        data.offset = Calendar.jsonFormat(offset, true);    this.ajax.getArchived(data, function(data) {        if(!offset)            self.setCache(data);        callback(data);    });}

Coffeescript looks like this:

12345678910111213 get: (offset, callback, limit) =>    data =        project_id: Projects.getCurrent().id        limit: limit or @default_limit    if offset        data.offset = Calendar.jsonFormat(offset, true)    @ajax.getArchived(data, (data) =>        if !offset            @setCache(data)        callback(data)    )

As you can see, the two look very similar, but my point is that coffeescript looks more brisk because all non-essential grammars are removed to preserve only the necessary elements.

Now let's take a look at the highlights of Coffeescript:

Highlight one: inheritance is simpler

JavaScript has a strong inheritance system, but the syntax is scary, coffeescript fixed a very elegant inheritance system to simulate many other languages in the class and inheritance mechanism:

12345678910 class Animal    constructor: (@name) ->    move: (meters) ->        alert @name + " moved " + meters + "m."class Snake extends Animal    move: ->        alert "Slithering..."        super 5

Highlight two: iteration of an array

I like the list derivation in Python in Coffeescript also has

12 list = [1, 2, 3, 4, 5]cubes = (math.cube num fornum inlist)

Array slices:

1 copy = list[0...list.length]

Array iterations:

1 countdown = (num fornum in[10..1])

Highlight Three: string iterations

For the insertion of the word A, Coffeescript borrowed Ruby's syntax, which simply constructs a string.

12 author = "Wittgenstein"quote  = "A picture is a fact. -- #{ author }"

Allow multiple lines of string:

123 mobyDick = "Call me Ishmael. Some years ago -never mind how long precisely -- having littleor no money in my purse, and nothing particular..."

Highlight four: Bind this

The This keyword is partially corrupted in JavaScript because his dynamic domain, Coffeescript, fixes these if you use the + = keyword (it automatically binds you to this or @)

1234567 Account = (customer, cart) ->    @customer = customer    @cart = cart    $(‘.shopping_cart‘).bind(‘click‘, (event) =>        @customer.purchase @cart    )

Explore Coffeescript

I just grabbed something from the surface of coffeescript, and more details are extracted from their site and annotated source code .

I'm still exploring Coffeescript, which is my favorite language so far, and honors belong to Jeremy Ashkenas. Happy programming, I also hope you can try a coffeescript.

[Coffeescript] Writing JavaScript code in a graceful way

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.