六个更小但很棒的ES6功能

ES6 has brought JavaScript developers a huge new set of features and syntax updates to be excited about.  Some of those language updates are quite large but some of them are small updates you would miss if you weren't careful -- that's why I wrote about Six Tiny But Awesome ES6 Features, a list of the little things that can make a big difference when you code for today's browsers.  I wanted to share with you six more gems that you can start using to reduce code and maximize efficiency.

ES6为JavaScript开发人员带来了大量令人兴奋的新功能和语法更新。 这些语言更新中的一些更新很大,但如果不小心,您可能会错过其中的一些小更新-这就是为什么我写了《 六小但很棒的ES6功能 》一书,列出了可以带来很大变化的小事情当您为当今的浏览器编码时。 我想与您分享另外六个gem,您可以开始使用它们来减少代码并最大化效率。

1.对象速记 (1.  Object Shorthand)

A new object creation shorthand syntax allows developers to create key => value objects without defining the key: the var name becomes the key and the var's value becomes the new object's value:

新的对象创建速记语法允许开发人员在不定义键的情况下创建键=>值对象:var名称成为键,而var的值成为新对象的值:

var x = 12;
var y = 'Yes!';
var z = { one: '1', two: '2' };

// The old way:
var obj = {
    x: x,
    y: y,
    z: z
};

var obj = { x, y, z };
/*
    {
        x: 12,
        y: "Yes!",
        z: { one: '1', two: '2' }
    }
*/


I can't tell you the number of times I've manually coded key => value properties in this exact same way -- now we simply have a shorter method of completing that task.

我无法告诉您以完全相同的方式手动编码键=>值属性的次数-现在,我们只是用一种较短的方法来完成该任务。

2.方法属性 (2.  Method Properties)

When it comes to these ES6 tips, it seems like I obsess over just avoiding adding the function keyword...and I guess this tip is no different.  In any case, we can shorten object function declarations a la:

当涉及到这些ES6技巧时,似乎我很着迷于避免添加function关键字……我想这个技巧也没有什么不同。 无论如何,我们可以缩短对象函数的声明,例如:


// Format: { myFn(param1) { ... } }
var davidwalsh = {
    makeItHappen(param) {
        /* do stuff */
    }
}

You have to admit that leaving off all of the function keyword madness does make for cleaner code and less maintenance.

您必须承认,省去所有function关键字madness确实可以使代码更简洁,维护更少。

3.块与立即执行的功能 (3.  Blocks vs. Immediately Executed Functions)

The pattern for creating immediately executing functions is a bit ugly:

创建立即执行功能的模式有点难看:


(function() {

   /* do stuff */

})();


With ES6 we can create a block with just {}, and with let, we can accomplish immediately executing function-like behavior without all the parens:

使用ES6,我们可以仅使用{}创建一个块,使用let ,我们可以立即执行类似函数的行为,而无需使用所有括号:


{ 
    let j = 12; 
    let divs = document.querySelectorAll('div');

    /* do more stuff */
}

j;  // ReferenceError: j is not defined...


If you declare a function within the block, it will leak out, but if you keep to let, you've essentially created an IEF without the parens.

如果在该块内声明一个函数,则该函数将泄漏出去,但如果继续let ,则实际上已创建了一个没有括号的IEF。

4. for循环并let (4.  for loops and let)

Because of variable hoisting within JavaScript, oftentimes we would either declare "useless" iterator variables at the top of blocks, code for(var x =..., or worst of all forget to do either of those and thus leak a global...just to iterate through a damn iterable.  ES6 fixes this annoyance, allowing us to use let as the cure:

由于JavaScript中的变量吊起,通常我们要么在块的顶部声明“无用的”迭代器变量,要么代码for(var x =... ,或者最糟糕的是忘记执行其中任何一个,从而泄漏全局变量。 。只是通过一个可迭代的迭代进行迭代。ES6修复了这种烦恼,使我们可以使用let作为治疗方法:

for(let x = 0; x <= elements.length; x++) {
  console.log(x); // x increments
}

x; // ReferenceError: x is not defined


In the near future we'll see let being used as much if not more than var.

在不远的将来,我们将看到let的使用量不超过var

5. getset课程 (5.  get and set for Classes)

As a member of the MooTools team, I was a huge fan of classes in JavaScript before JavaScript classes were really a thing. Now they're a thing:

作为MooTools小组的成员,在JavaScript类成为真正的事物之前,我是JavaScript类的忠实粉丝。 现在他们是一回事:


class Cart {
  constructor(total) {
      this._total = total;
  }
  get total() { return this._total; }
  set total(v) { this._total = Number(v); }

  get totalWithTax() { return parseInt(this._total * 1.1, 10); } /* 10% tax */
}

var cart = new Cart(100);

cart.totalWithTax === 110;


The best part is the new ability to create getters and setters for properties! No need to create special setting via functions -- these automatically execute when they're set via basic obj.prop = {value}.

最好的部分是创建属性的getter和setter的新功能! 无需通过函数创建特殊设置-通过基本obj.prop = {value}设置时,这些函数会自动执行。

6. startsWithendsWithincludes (6. startsWith, endsWith, and includes)

We've been coding our own basic String functions for way too long -- I remember doing so in the early MooTools days.  The startsWith, endsWith, and includes String functions are examples of such functions:

我们对自己的基本String函数进行编码的时间已经太久了-我记得在MooTools早期就这样做了。 startsWithendsWithincludes String函数就是此类函数的示例:


"MooTools".startsWith("Moo"); // true;
"MooTools".startsWith("moo"); // false;

"MooTools".endsWith("Tools"); // true;

"MooTools".includes("oo"); // true;


Seeing comon sense functions make their way to a language is incredibly satisfying;

看到常识功能已成为一种语言,这令人难以置信。

ES6 has been an incredible leap forward for JavaScript. The tips I've pointed out in this post and the previoius go to show that even the smallest of ES6 updates can make a big difference for maintainability. I can't wait to see what the next round of JavaScript updates provides us!

ES6对于JavaScript来说是不可思议的飞跃。 我在这篇文章中指出的技巧和先例将显示即使最小的ES6更新也可以对可维护性产生很大的影响。 我等不及要看下一轮JavaScript更新为我们提供了什么!

翻译自: https://davidwalsh.name/es6-features-ii

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值