Javascript Object.assign 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31764414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:10:03  来源:igfitidea点击:

Object.assign is not a function

javascriptgulpecmascript-6babeljs

提问by TIJ

I'm using babel with gulp and create a simple DOM library in ES6. But after running and when i'm going to use it, I got the Object.assign is not a functionin chrome console.

我在 gulp 中使用 babel 并在 ES6 中创建了一个简单的 DOM 库。但是在运行之后,当我要使用它时,我得到了Object.assign is not a functionchrome 控制台。

this is the gulp code

这是 gulp 代码

gulp.task('scripts', function() {
    return gulp.src(src + 'js/*.js')
      .pipe(babel())
      .pipe(concat('main.js'))
      .pipe(gulp.dest(dest + 'js'));
});

this is the class file

这是类文件

class DOM {
    constructor( selector ) {
        var elements = document.querySelectorAll(selector);

        this.length = elements.length;

        Object.assign(this, elements);
    }

    ...

}

const dom = selector => new DOM(selector);

and I'm using it in client side like dom('#elId');

我在客户端使用它 dom('#elId');

回答by Jacob Budin

As I suspect you already know, Google Chrome uses V8, which supports ECMAScript 5th edition. Object.assignis introduced in ECMAScript 6th edition.

我怀疑你已经知道,谷歌浏览器使用V8,它支持 ECMAScript 5th edition。Object.assign在 ECMAScript 第 6 版中引入。

In order to use these additions, you need to include the ES6 polyfillprovided by Babel:

为了使用这些添加,你需要包含Babel 提供的 ES6 polyfill

This will emulate a full ES6 environment. [...]

Available from the browser-polyfill.jsfile within a babel-corenpm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script>before it.

这将模拟完整的 ES6 环境。[...]

可从npm 版本中的browser-polyfill.js文件中获得babel-core。这需要在所有编译的 Babel 代码之前包含。您可以将其添加到已编译的代码中,也可以将其包含在 a<script>之前。

回答by Amo Wu

  1. Install babel-core:
  1. 安装babel-core

$ npm install babel-core --save-dev

$ npm install babel-core --save-dev

  1. Import polyfillmodule into your js:
  1. polyfill模块导入您的 js:

import 'babel-core/polyfill';

import 'babel-core/polyfill';

  1. Use babel to compile your code!
  1. 使用 babel 编译你的代码!