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

sec*_*age 6 javascript

I'm new to JavaScript. Just a question on using the spread operator on a class function. An example:

let personA = {
  name: "Tom",
  testFunction: function() {
    // ...
  }
};
let newArray = [];
newArray.push({ ...personA });
console.log(newArray);
Run Code Online (Sandbox Code Playgroud)

And the output is:

[{ name: 'Tom', testFunction: F}]
Run Code Online (Sandbox Code Playgroud)

But if I use a class, such as:

[{ name: 'Tom', testFunction: F}]
Run Code Online (Sandbox Code Playgroud)

The output is:

[{ name: 'Tom'}]
Run Code Online (Sandbox Code Playgroud)

So the function is missing. Isn't everything in JS an object? So why can I use the rest operator to get the method when using object literals but not with a class?

Cer*_*nce 9

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() {

    }
}

Run Code Online (Sandbox Code Playgroud)

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() {

    }
}

Run Code Online (Sandbox Code Playgroud)

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

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

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

console.log(Person.prototype.hasOwnProperty('testFunction'));
console.log(personA.hasOwnProperty('testFunction'));
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的。Spread 只能用于创建全新的普通对象字面量。它不能用于添加到现有对象或分配给类的“.prototype”,除非您使用“Object.assign”。只有“Object.assign”可以将一个对象的所有属性分配给另一个对象,而另一个对象*已经存在*。 (2认同)