Making the Most of the JavaScript Language

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
查看查看98 回复回复2 收藏收藏 分享淘帖 转播转播 分享分享 微信
查看: 98|回复: 2
收起左侧

Making the Most of the JavaScript Language

[复制链接]
瑶池 发表于 2016-8-8 07:41:30 | 显示全部楼层 |阅读模式
快来登录
获取最新的苹果动态资讯
收藏热门的iOS等技术干货
拷贝下载Swift Demo源代码

Despite having used JavaScript in production for 8 years, I only started learning how to write JavaScript properly in the past 2 years and from speaking to people I think there are many developers out there have had a similar experience. It seems that a large degree of us have picked up JavaScript as a supplement through writing websites in PHP, ASP etc.. Since the popularity of NodeJS and advancements in browsers however, JavaScript has been flung to the forefront of modern front-end web development.

In this article I want to share some of the things I feel every developer should do to get the most out of JavaScript nowadays. This is by no means an exhaustive list but I’ve tried to prioritise it in order of what I think are the most important.

JavaScript was born from chaos and due to this there are good and bad features that made it into the language. It’s hard to really understand what these are until you’ve learnt hard lessons from building software in other languages as well as JavaScript and then having to go back and maintain/extend said application. Here’s what I’ve learnt through the hard lessons I’ve experienced.




1. Leverage First Class Functions

First class functions turn a programming language into Lego™ for adults. In a nutshell, having first class functions means that JavaScript can pass functions as arguments, return a function as a result of another function and assign them to variables. This means you can do some very powerful things with much less code, in particular it enables functional programming. A simple real-world(ish) example:

[JavaScript] 纯文本查看 复制代码
var myArray = [1, 2, 3, 4, 5, 6]

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

var getTotal = function (arr) {
  return arr.reduce(add, 0);
};

getTotal(myArray); // => 21


On line 7 we assign an anonymous function to the getTotal variable. On line 8 we pass our add function as an argument to the reduce function. This allows us to create much higher level general purpose functions that save us having to repeat ourselves (adhering to the [url=https://en.wikipedia.org/wiki/Don't_repeat_yourself]DRY principle[/url]). It also allows us to do function composition, in our example we composed our getTotal from a reduce of the add function.




2. Learn the Built-in Array Methods

I’m not just talking about the obvious ones like Array.prototype.push or Array.prototype.splice. Some of the more useful ones that come to mind are:



Like in the first example you can use these in function composition to produce some much more general but powerful higher level functions. Most applications are dealing with the manipulation of sets of data and knowing what’s available on your tool-belt for moulding this data is invaluable.




3. Use ES6 (ES2015)

Arrow functions, let & const, destructuring, tail call optimisation and template strings are some of the better features of ES6. I would personally steer away from the use of the class keyword because this encourages the use of classical inheritance as well as constructor functions which can be more vulnerable to misuse and side-effects.

ES6 features introduce a fairly new way of writing JavaScript and warrant looking into in a bit more detail, exploring these features is perhaps a subset of this post which I might do as a follow-up next week.

Using most ES6 features in a browser/NodeJS environment (at the time of writing) require the use of a transpiler, the tool for the job is https://babeljs.io/. As primarily a web developer, I like to use babel along side browserify using a simple command to transpile my ES6 code into ES5 code like so:

[Bash shell] 纯文本查看 复制代码
npm install -g browserify babelify
browserify -t babelify es6code.js > es5code.js


If we were to re-write the first example in ES6 it might look like this:

[JavaScript] 纯文本查看 复制代码
const myArray = [1, 2, 3, 4, 5, 6]
const add = (a, b) => a + b;
const getTotal = (arr) => arr.reduce(add, 0);

getTotal(myArray); // => 21


This is way more terse and way way easier on the eye, this alone should be enough to pique your interest in ES6. One thing to bare in mind though is that some of the engine specific ES6 features might not work with transpilation.




4. Understand the Stumbling Blocks: Scoping, Closures and Type Coercion



4.1、Scoping

The best way to illustrate this is through a code example and I’m going to base it on a similar example from Douglass Crockfords book The Good Parts because it does the job well.

[JavaScript] 纯文本查看 复制代码
var foo = function () {
  var a = 2,
      b = 4;

  var bar = function () {
    var b = 9,
        c = 14;
    // Here: a is 2, b is 9 and c is 14

    a = a + b + c;
    // Here: a is 25, b is still 9 and c is still 14
  };

  // Here: a is 2, b is 4 and c is undefined

  bar();
  // Now: a is 21, b is still 4 and c is still undefined
};


You can see that where you declare your variables matters based on how the inner function is defined and how the side effect from the inner function causes the ‘a’ variable to change it’s value. Being clear with the declaration of variables can go a great way to building more reliable software. Keep functions as pure as possible with clearly defined inputs and predictable outputs.



4.2、Closures

Closures are a great way to maintain private variables in JavaScript but also seem to be a source of great misunderstanding. In basic terms a closure is gives you access to an outer functions scope from an inner function (AKA lexical scope), like ‘a’ in the previous scoping example. That’s basically it. Where it gets interesting is when you return a function from an outer function where the inner function accesses the scope of the outer function, the inner function will retain the outer functions scope past the lifetime of the outer function. That sounds really complicated so let’s explain it in an example:

[JavaScript] 纯文本查看 复制代码
var outer = function () {
  var a = 1; // variables declared outside of the 'inner' function declaration
  var b = 2;
  
  return function inner() {
    return a; // return 'a' that was defined in the outer function.
    // return b; // We could also access 'b' if we felt like it.
  };
};

var inner = outer(); // the outer function returns the inner function
inner(); // => 1 // the inner functions still remembers that 'a' was defined as '1' from the outer function




4.3、Type Coercion

Many a joke has been made at the expense of JavaScript due to it’s seemingly nonsensical type-coercion. The best thing to do to keep all the haters at bay is to use the trusty === which will do a strict comparison between objects which in most cases is what you want. The only time that won’t work is when you want to compare separate object literals, even if they have exactly the same properties and structure, they will never be equal because they are two completely separate objects. In this case just compare each of the properties of the objects, some libraries like underscorejs offer ways of doing a deep comparison which does the aforementioned.




5. Avoid Classical Inheritance

This might be controversial because the status quo for the software industry is to use classical inheritance. I daresay you’ve written a mighty fine application using classical inheritance but if you do then you’re probably not making the most out of JavaScript. You can write very lean and maintainable applications in JavaScript by using a more functional approach (have you spotted the theme yet). An application will inevitably change and if you’ve used a classical inheritance pattern then when you decide you want to use a particular object in another way to service another requirement then you have to inherit all the junk that comes with it. This is particularly bad when you want to unit test and you end up having to mock a whole bunch of requirements of the base class just to test something simple higher up the inheritance chain. It’s better to throw away the blueprints and start thinking of your program in terms of data flow and objects rather than classifications. Thinking in this way can greatly improve testability, maintainability and terseness of a program.




6. Keep on Learning and Don’t Lose Faith

Many people complain that JavaScript moves to fast and has too much churn but this is just due to people not learning the language and focusing on frameworks. JavaScript definitely has some bad things but it also has some pretty awesome things too and if you learn to embrace the positives then you can really get some good use out of it. I was predominantly a C# developer but since I’ve started learning JavaScript properly it’s become my language of choice due to it’s highly pliable nature. If you have the stomach then JavaScript is a great entry language into the world of functional programming, particularly when used with ReactJS. I honestly can’t recommend functional programming with JavaScript enough.

I hope this article helps spread the gospel of good JavaScript and equally I hope that from JavaScripts success that other languages will look to it for inspiration and not just stick to the status quo.




原文:Making the Most of the JavaScript Language

都看到这里了,就把这篇资料推荐给您的好朋友吧,让他们也感受一下。

回帖是一种美德,也是对楼主发帖的尊重和支持。

*声明:敏捷大拇指是全球最大的Swift开发者社区、苹果粉丝家园、智能移动门户,所载内容仅限于传递更多最新信息,并不意味赞同其观点或证实其描述;内容仅供参考,并非绝对正确的建议。本站不对上述信息的真实性、合法性、完整性做出保证;转载请注明来源并加上本站链接,敏捷大拇指将保留所有法律权益。如有疑问或建议,邮件至marketing@swifthumb.com

*联系:微信公众平台:“swifthumb” / 腾讯微博:@swifthumb / 新浪微博:@swifthumb / 官方QQ一群:343549891(满) / 官方QQ二群:245285613 ,需要报上用户名才会被同意进群,请先注册敏捷大拇指

嗯,不错!期待更多好内容,支持一把:
支持敏捷大拇指,用支付宝支付10.24元 支持敏捷大拇指,用微信支付10.24元
baddy 发表于 2016-8-8 18:34:06 | 显示全部楼层
幸好我英文过硬
苏格拉没有底 发表于 2016-8-11 02:06:12 | 显示全部楼层
可惜是英文,看起来累
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

做任务,领红包。
我要发帖

分享扩散

都看到这里了,就把这资料推荐给您的好朋友吧,让他们也感受一下。
您的每一位朋友访问此永久链接后,您都将获得相应的金钱积分奖励
热门推荐

合作伙伴

Swift小苹果

  • 北京治世天下科技有限公司
  • ©2014-2016 敏捷大拇指
  • 京ICP备14029482号
  • Powered by Discuz! X3.1 Licensed
  • swifthumb Wechat Code
  •   
快速回复 返回顶部 返回列表