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
Object.assign is not a function
提问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 function
in chrome console.
我在 gulp 中使用 babel 并在 ES6 中创建了一个简单的 DOM 库。但是在运行之后,当我要使用它时,我得到了Object.assign is not a function
chrome 控制台。
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.assign
is 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.js
file within ababel-core
npm 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
- Install
babel-core
:
- 安装
babel-core
:
$ npm install babel-core --save-dev
$ npm install babel-core --save-dev
- Import
polyfill
module into your js:
- 将
polyfill
模块导入您的 js:
import 'babel-core/polyfill';
import 'babel-core/polyfill';
- Use babel to compile your code!
- 使用 babel 编译你的代码!