問題描述
我正在使用 babel 和 gulp 并在 ES6 中創建一個簡單的 DOM 庫.但是在運行之后,當我要使用它時,我在 chrome 控制臺中得到了 Object.assign is not a function
.
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 代碼
gulp.task('scripts', function() {
return gulp.src(src + 'js/*.js')
.pipe(babel())
.pipe(concat('main.js'))
.pipe(gulp.dest(dest + 'js'));
});
這是類文件
class DOM {
constructor( selector ) {
var elements = document.querySelectorAll(selector);
this.length = elements.length;
Object.assign(this, elements);
}
...
}
const dom = selector => new DOM(selector);
我在客戶端使用它,例如 dom('#elId');
and I'm using it in client side like dom('#elId');
推薦答案
我懷疑你已經知道,谷歌瀏覽器使用 V8,支持 ECMAScript 第 5 版.Object.assign
在 ECMAScript 第 6 版中引入.
As I suspect you already know, Google Chrome uses V8, which supports ECMAScript 5th edition. Object.assign
is introduced in ECMAScript 6th edition.
為了使用這些添加,你需要包含 Babel 提供的 ES6 polyfill:
In order to use these additions, you need to include the ES6 polyfill provided by Babel:
這將模擬一個完整的 ES6 環境.[...]
This will emulate a full ES6 environment. [...]
可從 babel-core
npm 版本中的 browser-polyfill.js
文件獲得.這需要包含在所有編譯的 Babel 代碼之前.您可以將其添加到已編譯的代碼中,也可以將其包含在 <script>
之前.
Available from the browser-polyfill.js
file within a babel-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.
這篇關于Object.assign 不是函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!