Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

this is the gulp code

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');

like image 998
TIJ Avatar asked Aug 01 '15 17:08

TIJ


People also ask

What is object assign ()?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Is object assign a deep copy?

Object. assign does not copy prototype properties and methods. This method does not create a deep copy of Source Object, it makes a shallow copy of the data. For the properties containing reference or complex data, the reference is copied to the destination object, instead of creating a separate object.

Does object assign overwrite?

Object. assign() returns a target object. In case of a name collision between a source and target property, Object. assign() will overwrite the local property of the target object.

Can you use object assign with an array?

assign() method to convert an array to an object, e.g. const obj = Object. assign({}, arr) . The Object. assign method takes a target and source objects as parameters, applies the properties from the sources to the target and returns the result.


2 Answers

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

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

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

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.

like image 97
Jacob Budin Avatar answered Oct 10 '22 04:10

Jacob Budin


  1. Install babel-core:

$ npm install babel-core --save-dev

  1. Import polyfill module into your js:

import 'babel-core/polyfill';

  1. Use babel to compile your code!
like image 30
Amo Wu Avatar answered Oct 10 '22 05:10

Amo Wu