简体   繁体   中英

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. If we have object we get with this code only some properties from that 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?


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. "

You are creating a function and calling it below.

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

You should consider using Babel

which automatically transform ES6 to older versions.

This is the code that Babel generates from your code, which will will work with older versions:

"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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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