javascript功能_早期最受好评的javascript功能

javascript功能

JS is constantly evolving and in this article I would like to talk about what is still only at the stage of concept and first proposals. But the community has already appreciated these innovations and is looking forward to them.

JS在不断发展,在本文中,我想谈一谈仅在概念和首次提议阶段还剩下什么。 但是社区已经赞赏这些创新,并期待着它们。

JS has several levels of new feature approval. In this article, I will talk about the features that are at levels 0 and 1.

JS具有多个级别的新功能批准。 在本文中,我将讨论级别0和1的功能。

第一阶段的提案 (Stage 1 Proposals)

The first level has the following purposes:

第一级具有以下目的:

  • Make the case for the addition

    补充理由
  • Describe the shape of a solution

    描述解决方案的形状
  • Identify potential challenges

    找出潜在的挑战

Let’s take a look at the most anticipated stage 1 features:

让我们看一下第1阶段最令人期待的功能:

1.管道运营商 (1. The Pipeline Operator)

This proposal introduces a new operator |> similar to F#, OCaml, Elixir, Elm, Julia, Hack, and LiveScript, as well as UNIX pipes and Haskell's &. It's a backwards-compatible way of streamlining chained function calls in a readable, functional manner, and provides a practical alternative to extending built-in prototypes.

该建议引入了一个新的运算符|>类似于F#OCamlElixirElmJuliaHackLiveScript ,以及UNIX管道和Haskell& 。 这是一种向后兼容的方式,以一种可读的,功能化的方式简化了链式函数的调用,并为扩展内置原型提供了一种实用的选择。

The pipeline operator is essentially a useful syntactic sugar on a function call with a single argument. In other words, sqrt(64) is equivalent to 64 |> sqrt.

管道运算符本质上是带有单个参数的函数调用上的有用语法糖。 换句话说, sqrt(64)等效于64 |> sqrt

This allows for greater readability when chaining several functions together. For example, given the following functions:

将多个功能链接在一起时,这可以提高可读性。 例如,给定以下功能:

function doubleSay (str) {
  return str + ", " + str;
}
function capitalize (str) {
  return str[0].toUpperCase() + str.substring(1);
}
function exclaim (str) {
  return str + '!';
}


//the following invocations are equivalent:


let result = exclaim(capitalize(doubleSay("hello")));
result //=> "Hello, hello!"


let result = "hello"
  |> doubleSay
  |> capitalize
  |> exclaim;


result //=> "Hello, hello!"

More use cases: https://github.com/tc39/proposal-pipeline-operator/wiki/Example-Use-Cases

更多用例: https : //github.com/tc39/proposal-pipeline-operator/wiki/Example-Use-Cases

Read more about proposal: https://github.com/tc39/proposal-pipeline-operator

阅读有关提案的更多信息: https : //github.com/tc39/proposal-pipeline-operator

2.模式匹配 (2. Pattern Matching)

This proposal adds a pattern matching expression to the language, based on the existing Destructuring Binding Patterns.

该提议基于现有的Destructuring Binding Patterns向该语言添加了模式匹配表达式。

Example:

例:

const res = await fetch(jsonService)
case (res) {
  when {status: 200, headers: {'Content-Length': s}} ->
    console.log(`size is ${s}`),
  when {status: 404} ->
    console.log('JSON not found'),
  when {status} if (status >= 400) -> {
    throw new RequestError(res)
  },
}

Read more: https://github.com/tc39/proposal-pattern-matching

了解更多: https//github.com/tc39/proposal-pattern-matching

3.可观察的 (3. Observable)

This proposal introduces an Observable type to the ECMAScript standard library. The Observable type can be used to model push-based data sources such as DOM events, timer intervals, and sockets. In addition, observables are:

该建议将一个Observable类型引入ECMAScript标准库。 Observable类型可用于为基于推式的数据源建模,例如DOM事件,计时器间隔和套接字。 另外,可观察到的是:

  • Compositional: Observables can be composed with higher-order combinators.

    组成:可观察物可以由高阶组合器组成。

  • Lazy: Observables do not start emitting data until an observer has subscribed.

    惰性:观察者只有在观察者订阅之前才开始发射数据。

Example: Observing Keyboard Events

示例:观察键盘事件

Using the Observable constructor, we can create a function which returns an observable stream of events for an arbitrary DOM element and event type.

使用Observable构造函数,我们可以创建一个函数,该函数返回任意DOM元素和事件类型的可观察事件流。

function listen(element, eventName) {
    return new Observable(observer => {
        // Create an event handler which sends data to the sink
        let handler = event => observer.next(event);


        // Attach the event handler
        element.addEventListener(eventName, handler, true);


        // Return a cleanup function which will cancel the event stream
        return () => {
            // Detach the event handler from the element
            element.removeEventListener(eventName, handler, true);
        };
    });
}

We can then use standard combinators to filter and map the events in the stream, just like we would with an array.

然后,我们可以使用标准组合器来过滤和映射流中的事件,就像处理数组一样。

// Return an observable of special key down commands
function commandKeys(element) {
    let keyCommands = { "38": "up", "40": "down" };


    return listen(element, "keydown")
        .filter(event => event.keyCode in keyCommands)
        .map(event => keyCommands[event.keyCode])
}

Note: The “filter” and “map” methods are not included in this proposal. They may be added in a future version of this specification.

注意:“过滤器”和“地图”方法未包含在此建议中。 它们可能会在此规范的将来版本中添加。

When we want to consume the event stream, we subscribe with an observer.

当我们想使用事件流时,我们订阅一个观察者。

let subscription = commandKeys(inputElement).subscribe({
    next(val) { console.log("Received key command: " + val) },
    error(err) { console.log("Received an error: " + err) },
    complete() { console.log("Stream complete") },
});

The object returned by subscribe will allow us to cancel the subscription at any time. Upon cancelation, the Observable’s cleanup function will be executed.

订阅返回的对象将使我们可以随时取消订阅。 取消后,将执行Observable的清除功能。

// After calling this function, no more events will be sent
subscription.unsubscribe();

Read more: https://github.com/tc39/proposal-observable

了解更多: https//github.com/tc39/proposal-observable

4.部分应用程序语法 (4. Partial Application Syntax)

This proposal introduces a new syntax using the ? token in an argument list which allows you to partially apply an argument list to a call expression by acting as a placeholder for an argument.

本提案使用?引入了新语法? 参数列表中的标记,通过充当参数的占位符,您可以将参数列表部分地应用于调用表达式。

Examples:

例子:

const addOne = add(1, ?); // apply from the left
addOne(2); // 3


const addTen = add(?, 10); // apply from the right
addTen(2); // 12


// with pipeline
let newScore = player.score
  |> add(7, ?)
  |> clamp(0, 100, ?); // shallow stack, the pipe to `clamp` is the same frame as the pipe to `add`.


// partial template strings
const Diagnostics = {
  unexpected_token: `Unexpected token: ${?}`,
  name_not_found: `'${?}' not found.`
};
Diagnostics.name_not_found("foo"); // "'foo' not found."

Read more: https://github.com/tc39/proposal-partial-application

了解更多: https//github.com/tc39/proposal-partial-application

5.二进制AST (5. Binary AST)

A binary encoding based on an efficient abstract syntax tree representation of JavaScript syntax is proposed. This is a new, alternate encoding of the surface syntax, with a fairly close bidirectional mapping to the text representation. New semantics are currently limited to:

提出了一种基于JavaScript语法的有效抽象语法树表示的二进制编码。 这是表面语法的一种新的替代编码,具有相当接近的双向映射到文本表示形式。 当前,新语义仅限于:

  • deferring early errors

    推迟早期错误
  • changing Function.prototype.toString behavior

    更改Function.prototype.toString行为

  • requiring UTF-8

    需要UTF-8

To further speed up parsing, it is proposed to encode static semantics as implementation hints, and verify them as deferred assertions.

为了进一步加快解析速度,建议将静态语义编码为实现提示,并将其验证为延迟的断言。

For this AST format automatically derive from the ECMA-262 grammar is not proposed since it is too verbose to be an efficient tree representation, and as such it would require a lot of flattening and inlining. Additionally, this might restrict the evolution of the JavaScript specification by effectively making the grammar a normative specification of the binary format.

对于此AST格式,不建议自动从ECMA-262语法中获取语法,因为它过于冗长而无法成为有效的树表示形式,因此需要大量的拼合和内联。 另外,通过有效地使语法成为二进制格式的规范性规范,这可能会限制JavaScript规范的发展。

Instead, a separate tree grammar is proposed, with annotations on AST nodes that only express information about the syntax. There are several existing tree grammars which are taken as a starting point, such as Babylon or Shift AST.

取而代之的是,提出了单独的树语法,在AST节点上带有仅表示有关语法信息的注释。 有几种现有的树语法作为起点,例如巴比伦或Shift AST。

Borrowing from the WebAssembly approach, the binary encoding would be split into 3 layers:

借鉴WebAssembly方法,二进制编码将分为3层:

  1. A simple binary encoding of the AST nodes using basic primitives (e.g., strings, numbers, tuples)

    使用基本原语(例如,字符串,数字,元组)对AST节点进行简单的二进制编码
  2. Additional structural compression on top of the previous layer, leveraging knowledge about the nature of the format of the file and the AST (e.g., constant tables)

    利用有关文件格式和AST的性质的知识(例如常量表),在上一层之上进行附加的结构压缩
  3. A generic compression algorithm like gzip or Brotli.

    通用压缩算法,例如gzip或Brotli。

It is expected the format to be output by existing compilers such as Babel and TypeScript, and by bundlers such as WebPack.

预计格式将由现有的编译器(例如Babel和TypeScript)以及捆绑器(例如WebPack)输出。

Read more: https://github.com/tc39/proposal-binary-ast

了解更多: https//github.com/tc39/proposal-binary-ast

6.内置模块 (6. Built In Modules)

To enable developers to access common functionality provided by the JavaScript engine it is proposed creating modules built into the host. This will allow library code bundled with the program to shift towards being available on the host JavaScript implementations.

为了使开发人员能够访问JavaScript引擎提供的通用功能,建议创建内置在主机中的模块。 这将使与程序捆绑在一起的库代码转向可在宿主JavaScript实现上使用的代码。

Having a standard library readily available at runtime means programs won’t have to include the functionality available in the standard library, reducing the download and startup cost of the program. The functionality will also be standardized across implementations giving developer consistency in quality, behavior and speed. For some JavaScript engines, built in modules will allow them to reduce application memory footprint

在运行时随时可以使用标准库意味着程序不必包含标准库中可用的功能,从而减少了程序的下载和启动成本。 该功能还将在各种实现中进行标准化,从而使开发人员在质量,行为和速度上保持一致。 对于某些JavaScript引擎,内置模块将允许它们减少应用程序内存占用量

Although JavaScript engines already has the notion of a common library through the global object, the standard library components can be accessed using the current asynchronous import() API. Module scripts can also access built in library components using the import syntax. Traditional script code will be able to access these same standard library components through a new synchronous API, importNow(). Most of these mechanism should already be familiar to developers, allowing them to opt-in to this built in library functionality with little effort.

尽管JavaScript引擎已经通过全局对象有了公共库的概念,但是可以使用当前的异步import() API访问标准库组件。 模块脚本还可以使用import语法访问内置库组件。 传统脚本代码将能够通过新的同步API importNow()访问这些相同的标准库组件。 这些机制中的大多数应该已经为开发人员所熟悉,从而使他们可以毫不费力地选择加入此内置库功能。

Modules for the standard library should be able to be written in plain JavaScript for the most part but for hot pieces of code the engine could provide a native implementation.

标准库的模块在大多数情况下应该能够用普通JavaScript编写,但是对于热门代码,引擎可以提供本机实现。

Read more: https://github.com/tc39/proposal-built-in-modules

了解更多: https//github.com/tc39/proposal-built-in-modules

7. do表情 (7. do expressions)

Write in an expression-oriented style, scoping variables as locally as possible:

以面向表达式的风格编写,尽可能在局部范围内定义变量:

let x = do {
  let tmp = f();
  tmp * tmp + 1
};

Use conditional statements as expressions, instead of awkward nested ternaries:

使用条件语句作为表达式,而不是笨拙的嵌套三元组:

let x = do {
  if (foo()) { f() }
  else if (bar()) { g() }
  else { h() }
};

Especially nice for templating languages like JSX:

对于模板化JSX之类的语言特别好:

return (
  <nav>
    <Home />
    {
      do {
        if (loggedIn) {
          <LogoutButton />
        } else {
          <LoginButton />
        }
      }
    }
  </nav>
)

Read more: https://github.com/tc39/proposal-do-expressions

了解更多: https//github.com/tc39/proposal-do-expressions

8.切片符号 (8. Slice notation)

The slice notation provides an ergonomic alternative to the various slice methods present on Array.prototype, TypedArray.prototype, etc.

切片符号为Array.prototype,TypedArray.prototype等上存在的各种切片方法提供了符合人体工程学的选择。

const arr = ['a', 'b', 'c', 'd'];


arr[1:3];
// → ['b', 'c']


arr.slice(1, 3);
// → ['b', 'c']

This notation can be used for slice operations on primitives like Array and TypedArray.

此表示法可用于对Array和TypedArray等原语进行切片操作。

Read more: https://github.com/tc39/proposal-slice-notation/

了解更多: https//github.com/tc39/proposal-slice-notation/

9.标准库UUID (9. Standard library UUID)

The JavaScript standard library UUID describes an API for generating character encoded Universally Unique Identifiers (UUID) based on IETF RFC 4122, available for import in JavaScript engines.

JavaScript标准库UUID描述了一个API,用于基于IETF RFC 4122生成字符编码的通用唯一标识符(UUID),可将其导入JavaScript引擎中。

The UUID standard library provides an API for generating RFC 4122 identifiers.

UUID标准库提供了用于生成RFC 4122标识符的API。

The only export of the UUID library that is initially supported is randomUUID(), a method which implements the version 4 "Algorithm for Creating a UUID from Truly Random or Pseudo-Random Numbers", and returns the string representation (as described in RFC-4122).

最初支持的UUID库的唯一导出是randomUUID() ,该方法实现版本4“用于从真正随机数或伪随机数创建UUID的算法” ,并返回字符串表示形式(如RFC- 4122)

Read more: https://github.com/tc39/proposal-uuid

了解更多: https//github.com/tc39/proposal-uuid

There are much more interesting Stage 1 proposals, read about them here — https://github.com/tc39/proposals/blob/master/stage-1-proposals.md

第1阶段还有更多有趣的建议,请在此处阅读有关它们的信息-https: //github.com/tc39/proposals/blob/master/stage-1-proposals.md

阶段0提案 (Stage 0 Proposals)

Stage 0 allow input into the specification. At level 0, there are only concepts for new features. But there are 2 that are worthy of attention.

阶段0允许输入规范。 在级别0,只有新功能的概念。 但是有两个值得关注。

Let’s take a look at them:

让我们看看它们:

1.此绑定语法 (1. This-Binding Syntax)

This proposal introduces a new operator :: which performs this binding and method extraction.

该建议引入了一个新的运算符:: ,它执行this绑定和方法提取。

//Using an iterator library implemented as a module of "virtual methods":
import { map, takeWhile, forEach } from "iterlib";


getPlayers()
::map(x => x.character())
::takeWhile(x => x.strength > 100)
::forEach(x => console.log(x));


//Using a jQuery-like library of virtual methods:
// Create bindings for just the methods that we need
let { find, html } = jake;


// Find all the divs with class="myClass", then get all of the "p"s and
// replace their content.
document.querySelectorAll("div.myClass")::find("p")::html("hahaha");


//Using method extraction to print the eventual value of a promise to the console:
Promise.resolve(123).then(::console.log);


//Using method extraction to call an object method when a DOM event occurs:
$(".some-link").on("click", ::view.reset);

Read more: https://github.com/tc39/proposal-bind-operator

阅读更多: https : //github.com/tc39/proposal-bind-operator

2.嵌套的import报关单 (2. Nested import declarations)

This proposal argues for relaxing the current restriction that import declarations may appear only at the top level of a module.

该建议主张放宽当前的限制,即import声明只能出现在模块的顶层。

Specifically, this proposal would allow import declarations that are

具体而言,该提案将允许import报关是

  1. nestable within functions and blocks, enabling multiple new and worthwhile import idioms;

    可嵌套在函数和块中,从而启用了多个新的和有价值的import习惯用法;

  2. hoisted to the beginning of the enclosing scope; that is, declarative rather than imperative;

    吊到封闭范围的开头; 也就是说,声明式而不是命令式

  3. lexically scoped to the enclosing block;

    从词法上讲,范围是封闭的块;
  4. synchronously evaluated, with clear and manageable consequences for runtime module fetching; and

    进行了同步评估,为运行时模块的获取带来了明确且可管理的结果; 和
  5. backwards compatible with the semantics of existing top-level import declarations.

    向后兼容现有顶级import声明的语义。

At this time, no changes are proposed regarding the placement or semantics of export declarations. In the opinion of the author, keeping all export declarations at the top level remains important for many of the static properties of the ECMAScript module system.

目前,未提出有关export声明的位置或语义的任何更改。 作者认为,对于ECMAScript模块系统的许多静态属性,将所有export声明都保留在顶层仍然很重要。

// Execution might hit this debugger statement before the "./xy" module is
// imported, if it has not been imported before.
debugger;
{
  import { x, y } from "./xy";
}


console.log("x", getX());


// Imperatively import { x } from "./xy", and return it.
function getX() {
  import { x } from "./xy";
  return x;
}


// If you care about the latest live value of x, return a closure.
function getXFn() {
  import { x } from "./xy";
  return () => x;
}


const getX2 = getXFn();


setTimeout(() => {
  console.log("current x:", getX2());
}, delay);

Read more: https://github.com/benjamn/reify/blob/master/PROPOSAL.md

阅读更多: https : //github.com/benjamn/reify/blob/master/PROPOSAL.md

There are much more Stage 0 proposals, read about them here — https://github.com/tc39/proposals/blob/master/stage-0-proposals.md

阶段0提案更多,请在此处阅读有关它们的信息-https: //github.com/tc39/proposals/blob/master/stage-0-proposals.md

Thanks for reading!

谢谢阅读!

P.S. If you want to know more about the most expected features — follow me!

PS:如果您想了解更多有关最期望的功能的信息,请跟我来!

翻译自: https://medium.com/dev-genius/top-starred-javascript-features-at-early-stage-982de948f2ae

javascript功能

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值