Why can I not use the spread operator on a class function?

The spread operator ... only gets the enumerable properties on the object itself.

name is a property of an instance of the class and testFunction is a property of the prototype of the class so being that testFunction is not actually a property of personA the spread operator doesn't deal with it.

I just copied and pasted your code into the JavaScript console then typed personA enter which made personA inspectable.

Expanding it you can see name is a property of personA (or rather a property of the object that personA references) but testFunction and constructor are properties of the class prototype for Person

enter image description here

Note that some people suggest I say something about 'own' properties. I find that to be nonsense.

Here's an example of what I mean

a = { fruit: 'banana', collection: 'bunch' };
b = { animal: 'dog', group: 'pack' };

c = {...a}

What is the object c references? It's a new object with properties 'fruit' and 'collection'. Do need to mention that b's properties are not considered? NO!

Similarly the same holds true for the object personA references. That object does not have enumerable properties testFunction nor constructor. They are entirely irrelevent as they are not part of the object itself. They are on a separate object entirely as pointed out by the debugger screenshot.


Object spread only copies enumerable own properties:

It copies own enumerable properties from a provided object onto a new object.

With

class Person {
    constructor(name) { 
        this.name = name;
    }
    testFunction() {

    }
}

the testFunction is on Person.prototype, not on a Person instance, so it doesn't get copied; it's not an own property.

class Person {
    constructor(name) { 
        this.name = name;
    }
    testFunction() {

    }
}
let personA = new Person("Tom");

console.log(Person.prototype.hasOwnProperty('testFunction'));
console.log(personA.hasOwnProperty('testFunction'));

If you assign testFunction to the instance in the constructor, it'll get copied:

class Person {
  constructor(name) {
    this.name = name;
    this.testFunction = this.testFunction;
  }
  testFunction() {

  }
}
let personA = new Person("Tom");
console.log(personA.hasOwnProperty('testFunction'));
let newArray = [];
newArray.push({ ...personA });
console.log(newArray);

Tags:

Javascript