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:
Run Code Online (Sandbox Code Playgroud)[{ name: 'Tom', testFunction: F}]
But if I use a class, such as:
[{ name: 'Tom', testFunction: F}]
Run Code Online (Sandbox Code Playgroud)
The output is:
Run Code Online (Sandbox Code Playgroud)[{ name: 'Tom'}]
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?
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)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |