Home >Web Front-end >JS Tutorial >The death and life of JavaScript

The death and life of JavaScript

高洛峰
高洛峰Original
2016-11-25 11:32:251092browse

JavaScript success comes from being in the right place at the right time. The rise of JavaScript is closely related to browser support. You see, VBScript is not so lucky.

JavaScript is popular, but it has inherent flaws. Brendan Eich designed JavaScript in only 10 days. As the father of JavaScript, Brendan Eich said:

It’s better to say that I hate JavaScript than I love it. It is the product of a one-night stand between C language and Self language. Dr. Johnson, a British litterateur in the 18th century, said it well: "Its excellence is not originality; its originality is not excellence."
The most obvious shortcoming of JavaScript is its grammar.

Poor and verbose syntax for optional parameters and default values

function(a, b, option) {
optionoption = option || {};
// ...
}
In the above code, option is optional Parameters, when not passed, the default value is {}. However, the option value passed may be a false value (falsy value). Strictly written, the following judgment must be made:

function(a, b, option) {
option = arguments.length > 2 ? option : {};
// ...
}
Note: option = typeof option ! == undefined ? option :{} may also be wrong, because what is passed may be undefined. When the b parameter is not required and is deleted, the judgment based on arguments.length can easily lead to forgetting to modify it and making an error:

function(a, option) {
option = arguments.length > 2 ? option : {};
// ...
}
It would be great if the following syntax could be added:

function(a, b, option = {}) {
// ...
}
Let
closures are powerful and annoying:

for (var i=0, ilen=elements.length; i var element = elements[i];
LIB_addEventListener(element, click, function(event) {
alert(I was originally number + i);
});
}
The above code often appears in interview questions. The solution is to wrap it in another layer:

for (var i=0, ilen=elements.length; i var element = elements[i];
(function(num) {
LIB_addEventListener(element, click, function(event) {
alert(I was originally number + num);
});
}(i)) ;
}
It would be great if let syntax was directly supported:

for (var i=0, ilen=elements.length; i var element = elements[i];
let (num = i) {
LIB_addEventListener(element, function(event) {
alert(I was originally number + num);
});
};
}
Module
Module mode is a helpless choice:

If it is natively supported How great:

module event {

// private variables
var listeners = [];

export function addEventListener(f) {
listeners.push(f);
}

export function clearEventListeners() {
Listeners = [];
}

// ...
}

(function() {

import event;

// ...
}());
Inheritance
JavaScript must go through the prototype chain To implement inheritance:

function Employee(first, last, position) {
// call the superclass constructor
Person.call(this, first, last);
this.position = position;
};
// inherit from Person
Employee.prototype = Object.create(Person.prototype);
EmployeeEmployee.prototype.constructor = Employee;

// define an overridding toString() method
Employee.prototype.toString = function() {
// call superclasss overridden toString() method
return Person.prototype.toString.call(this) +
is a + this.position;
};
It would be great if it could be written like this:

class Employee extends Person {
constructor(first, last, position) {
super(first, last);
public positionposition = position;
}

update(camera) {
return super.update() + is a + position;
}
}
Impressions
The ECMAScript committee has realized that JavaScript has shortcomings at the grammatical level. In the Harmony specification, all the above syntaxes have been proposed.

When can we use the above syntax?

As long as there is a macro (Macro)
The macro feature of Lisp language is very powerful. Through macros, you can define the desired syntax format according to your own preferences. The macro feature makes Lisp a "programmable programming language".

JavaScript does not have macros. Adding macro features to C-like languages ​​is still a research topic and is very difficult.

As long as there are macros, we can customize the syntax. But the macro feature of JavaScript is far away, so we should find other ways.

Harmony
The syntax extension in the Harmony specification may be the dream of all of us. Harmony has the potential to become an ECMAScript 6 specification. Until then, we need to wait and be patient.

As of May 2011, w3school shows that IE6’s market share is still 2.4%. Net Market Share shows that IE6 has a market share of 10.36%. IE7 also has a lot of market share. These old browsers will not disappear from the market in the short term. For commercial companies, such as Amazon, it is impossible to give up these users. Terrible situation. (Mainland China is even worse, IE6/7 still accounts for more than 40% of the market share)

We cannot rely on calls like "IE be damned" to get users to upgrade. I have heard a saying: IE users only upgrade their browser when they change their computer hardware. Sadly, for ordinary users, existing hardware is enough to receive emails, access Facebook and Twitter. There's no reason for them to spend any money.

Goggle Apps recently announced that it will stop supporting IE7 starting from August 2011.

According to various conservative estimates, Amazon website developers will have to wait until 2023 to use the Harmony syntax extension!

In your prime, are you willing to wait more than 10 years before using these useful grammars?

JavaScript is dead
Cause of death: semicolon cancer. (semicolon cancer. The author’s joke, meaning that grammar causes the death of JavaScript)

Through the above analysis, it can be seen that the implementation of macro features is too difficult, and the implementation of Harmony specifications is far away. A large number of programmers have begun to write JavaScript, and many of them are tired of or starting to get tired of JavaScript's long and bad syntax. We need new syntax and we don't want to wait! JavaScript, as a source code writing language, is dead!

Mr. JavaScript, you had a glorious reign. We have had sweet memories with you and have produced many interesting applications together. May the deceased rest in peace.

JavaScript is here to stay
Programmers like to control their own destiny. As a source code writing language, JavaScript is dead. We can choose or create another better source code language and compile it into the ECMAScript 3 syntax format.

The new life of JavaScript is as a compilation target.

Languages ​​compiled into JavaScript
There are many languages ​​​​that can be compiled into JavaScript. In 1997, I collected a list. Includes:

JavaScript extension languages: dead ECMAScript 4, Narrative Script, Objective-J.
Existing languages: Scheme, Common Lisp, Smalltalk, Ruby, Python, Java, C#, Haskell, etc.
There are also some brand-new languages: HaXe, Milescript, Links, Flapjax, specially designed for web programming.
Among these compiler projects, Goggle's GWT Java-to-JavaScript compiler is probably the most successful one. However, the tragedy is that GWT is rarely seen in real projects. The reasons are as follows:

1. Maintenance costs are high. The compiler may have bugs. Suppose you find a bug in the compiler in a large project. As a maintainer, in addition to maintaining the source code, you also have to maintain the compiler. Oh my god, do you have what it takes? Even if you have this ability, the CEO is not willing to spend this money.

2. Debugging is troublesome. Firebug reported an error and reported the compiled line number. The boss stands behind you: Hurry up, young man! But which line of source code does this damn compiled code correspond to?

3. Unable to recruit people. Suppose you are developing a project using Objective-J, but you don't have enough people. Hurry and recruit people, HR said that out of 1,000 people, only 100 have heard of Objective-J, and the other 900 have only heard of JavaScript. The end result is that every time you find a new person, you have to train them first, which is really terrible.

Although compilers have the above disadvantages, various compilers are still springing up in large numbers. There's no doubt that writing a JavaScript compiler is pretty cool. Pay me and I'd like to write one too.

In the above list of compilers, there is a very famous one that has caused a lot of sensation: CoffeeScript. Let's talk about it.
CoffeeScript
Why is CoffeeScript so popular? I haven't figured it out until now. Is it because of the meaning given to white space, or is it function syntax with arrows? Every time I think about this, my stomach can't help but feel turbulent. CoffeeScript has many new features: default parameter values, rest parameters, spread, destructuring, fixing the whole implied global mess... Many features of CoffeeScript are part of the Harmony specification and may be directly supported in future browsers. CoffeeScript provides instant gratification.

@pyronicide on Twitter: #coffeescript supports function default parameter values, which is so exciting.
At the TXJS 2011 conference, Douglas Crockford also said: CoffeeScript is undoubtedly a good thing.

The author of CoffeeScript: Accelerated JavaScript Development said:

@trevorburnham
[...] CoffeeScript does not turn JS into Ruby or Python, but uses a set of syntax to better utilize the inherent excellence of JavaScript.


Douglas Crockford believes that JavaScript has good aspects and developed the JSLint tool to ensure that developers stay away from the bad aspects of JavaScript. The subset of syntax allowed by JSLint deserves its own name, we might as well call it GoodScript.

ECMAScript 5 introduced the "use strict" directive to restrict the use of syntax such as with.

CoffeeScript, GoodScript, and ECMAScript 5 have the same goal: to stay away from the crap while providing you with useful, safe language features.

GoodScript does not provide new features. Most browsers do not support the strict mode of ECMAScript 5 yet. However, we don't want to wait.

The remaining option is CoffeeScript. Benefits:

Especially suitable for web development. This may be something other JavaScript compilers don't do or don't do well.
CoffeeScript encapsulates JavaScript appropriately. This makes the compiled code easier to read and debugging less difficult.
CoffeeScript looks like a set of macros for writing JavaScript code.

CoffeeScript's compiler provides a client version. In this way, users can choose freely and developers can quickly develop new functions without being restricted by standards. It's nice to have CoffeeScript driven by the vision and needs of the community.

Invent your own language
You can do it, it will be a good exercise. As a developer of JavaScript compilers, you will have great honor.

The danger of inventing your own language is this: you think you will end up doing it better than JavaScript. Language design is hard, and I bet your language will have a hard time growing market share. CoffeeScript has not yet reached adolescence, and there are already complaints.

You may be proud that your compiler can compile simple, readable code. However, when encountering special circumstances, you will be so depressed that you want to hit the wall.

Idioms will appear in your language. Then, you'll soon find someone breaking these idioms (unless your language happens to support macros).

No more sarcastic remarks. Go develop your own language now and you will become a very good programmer.

What does JavaScript lack as a compilation target language?
As a compilation target language, JavaScript is given a new lease of life. In the JSConf.US talk, Brendan Eich said: The purpose of the Harmony specification is to make JavaScript a better compilation target.

Compiled JavaScript may run less efficiently than handwritten JavaScript, just like compiled C may run less efficiently than handwritten assembly language. Fortunately, the bottleneck of JavaScript is mainly in DOM operations, and the efficiency loss of the language itself is relatively acceptable. Although this is said, some efficient source code languages ​​may be extremely inefficient due to problems with JavaScript itself after compilation, so that they cannot be used in real environments. There are already some features in the Harmony specification to ensure that this kind of problem is avoided.

Reasonable tail call
function isEven(number) {
if (number === 0) {
                                                                                               . isOdd( number) {
if (number === 0) {
return false;
}
else {
return isEven(number - 1);
}
}

isEven(100000); // InternalError: too much recursion
The above code will cause stack overflow when run in current browsers.

Can be optimized with trampolines techniques:

function bounce(ret) {
while (typeof ret === function) {
retret = ret();
}
return ret;
}

function isEven(number) {
if (number === 0) {
         return true; {
if (number === 0) {
         return false;                                                                                                                       ,,                                                  ,,           return false; Even(100000);}); // true
Through bounce method, when running isOdd(99999), isEven(100000) has been completed and exited from the stack, so it will not cause overflow.

Fortunately, ECMAScript Harmony has taken this into consideration and will automatically optimize it. This is beneficial to both program developers and compiler developers.

Lambdas
lambdas are not magical. In short, lambda is something callable, such as function, but needs to comply with TCP (Tennent’s Correspondence Principle). TCP requirement: Encapsulating an expression or code block with an adjacent lambda does not change the meaning of the encapsulated code.

Obviously, JavaScript functions are not lambdas:

function one() {
return 1;
}

one(); // 1
After encapsulation, the return value has changed:

function one() {
(function() {
}());

}

one(); // undefined

For a block of code that accepts two parameters and sums them, the lambda syntax is proposed to be written as: {|a , b| a + b}

For the above example, using lambda packaging will ensure that the return value is the same as before packaging:

function one() {

({||
}());
}

one(); // The strawman proposal for the 1
lambda block has not yet been promoted to the Harmony specification, let's work on it together.

What is the browser missing?
The rise and fall of JavaScript cannot be separated from the browser. The new life of JavaScript also requires reliable support from browsers.

Mozilla launched a SourceMap project, which allows the corresponding lines of code to be mapped back to the source code when debugging compiled code. This is so cool and can greatly reduce debugging costs.

I heard that the guys at Webkit are doing the same thing, but unfortunately I can’t find any evidence.

Proficient in several languages

JavaScript’s monopoly on browsers means that front-end programmers all speak the same language. However, the differences in compilers will make it difficult for CoffeeScript programmers to immediately understand JavaScript code based on Traceur.

This disagreement is inevitable. For example, there is C, as well as various languages ​​such as C++ and Objective-C. The same goes for Java. You can also choose Clojure or JRuby based on JVM. Microsoft is aware of this and developed CLR. C#, Basic, IronPython, etc. can all run on CLR.


Communication barriers in the front-end are not new. It is difficult for a Dojo programmer to immediately understand code based on jQuery or YUI.

Having multiple source code writing languages ​​will increase communication barriers in the community. Programmers still need to know JavaScript. Programmers still need to know JavaScript, at least for a while. But in just a few years, they may know other source languages ​​better.

Summary
It’s great to have the opportunity to witness the new life of JavaScript. In the competition for JavaScript compilation, it's hard to say who will ultimately win market share, but there's no doubt it will be interesting. Today, CoffeeScript is poised to take off, but I'm sure many other successful source code languages ​​will follow.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn