简体   繁体   English

我如何将这段 ES6 代码转换为旧版本的 javascript

[英]How can i transform this piece of code of ES6 into older version of javascript

I've found one solution written in ES 6 but i don't know how can i transform it on older version of java script so i cant understand it better.我找到了一个用 ES 6 编写的解决方案,但我不知道如何在旧版本的 java 脚本上对其进行转换,所以我无法更好地理解它。 If we have object we get with this code only some properties from that object.如果我们有 object,我们使用此代码仅从该 object 中获得一些属性。 But i don't understand what is happening here.但我不明白这里发生了什么。 what means (obj) at the end and how looks this code in older version of java script?最后是什么意思(obj)以及这个代码在旧版本的 java 脚本中的外观如何?


const obj = {a:1, b:2, c:3, d:4, e:5 };
const result = (({a,b,c}) => ({a, b, c}))(obj);
console.log(result);

It goes like this:它是这样的:

 var obj = {a:1, b:2, c:3, d:4, e:5 }; var result = (function(o) { return { a: oa, b: ob, c: o.c }; })(obj); console.log(result);

and to be more descriptive, this part:为了更具描述性,这部分:

var result = (function(o) {
    return { a: o.a, b: o.b, c: o.c };
})(obj);

means " create an anonymous function that takes an object argument and returns a new object, and then execute it immediately with obj as an argument and assign the result to the result variable. "意思是“创建一个匿名的 function,它接受一个 object 参数并返回一个新的 object,然后立即以obj作为参数执行它并将结果分配给result变量。

You are creating a function and calling it below.您正在创建 function 并在下面调用它。

This is the same:这是一样的:

var obj = {a:1, b:2, c:3, d:4, e:5 };

var result = function(obj) {
  return {
    a: obj.a,
    b: obj.b,
    c: obj.c,
  }
}

result(obj);

console.log(result);

You can use Babel tool to transpile modern code:您可以使用 Babel 工具转译现代代码:

Babel通天塔

You should consider using Babel你应该考虑使用Babel

which automatically transform ES6 to older versions.它会自动将 ES6 转换为旧版本。

This is the code that Babel generates from your code, which will will work with older versions:这是 Babel 从您的代码生成的代码,它将适用于旧版本:

"use strict";

var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5
};

var result = function (_ref) {
  var a = _ref.a,
      b = _ref.b,
      c = _ref.c;
  return {
    a: a,
    b: b,
    c: c
  };
}(obj);

console.log(result); 

I would first ask what exactly You mean with 'older version', anyway the following is ES3 compliant, and should clarify:我首先要问一下“旧版本”到底是什么意思,无论如何,以下内容符合 ES3,并且应该澄清:

var obj = {a:1, b:2, c:3, d:4, e:5 };
function middleFun(o) {
  return {a: o.a, b: o.b, c: o.c}
}
var result = middleFun(obj)
console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM