Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

ES6中扩展运算符的背后原理是什么?如果扩展运算符的背后原理是调用遍历器的话,为何普通对象还能够使用扩展运算符呢?

ES6中扩展运算符的背后原理是什么?如果扩展运算符的背后原理是调用遍历器的话,为何普通对象还能够使用扩展运算符呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

如果是关心规范如何定义的,那看这里就对了spec

如果想知道一些主流的编译工具里面具体是如何实现的,那我们就来看看babel吧。

下面这段代码是经过@babel/core @babel/cli @babel/preset-env 处理的。

源码:

const arr = [1, 2, 3]

const obj = {
  name: 'hello'
}

console.log(...arr);

console.log({...obj});

编译后:

"use strict";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var arr = [1, 2, 3];
var obj = {
  name: 'hello'
};

// 如果是数组,会直接使用数据方法处理
console.log([].concat(arr));

// 如果是object,使用内置的工具函数把属性拷贝出来
console.log(_objectSpread({}, obj));

代码并不多,还是可以阅读一下的


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...