Reputation: 2939
I'm reading later chapters of the Adam Freeman Angular book, he has an example like this:
if(id != null) {
Object.assign(this.product, model.getProduct(id) || new Product());
}
Why is Object.assign used instead of just do this?
this.product = model.getProduct(id) || new Product();
Does it wait for the model.getProduct(id) to return or some other magic? as I can't see why you have to do this instead of just assign it straight onto your object.
I've seen it come up in how to clone an object but again why not just assign it, does it make less work for angular, so it only tracks what has changed?
Update: So reading the comments it seems that if I have a plain old object that I don't have special properties on, so a product comes from an API then I can just assign (=) that to the product and not bother with Object.assign or ... spreading it.
Upvotes: 1
Views: 83
Reputation: 33779
As stated in the Mozilla Developer docs, Object.assign()
copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
The docs also contains an example:
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
In contrast, a simple =
will assign the object on the left hand side to the object on the right hand side, without caring about the previous state of the object on the left hand side.
See also the Spread in object literals paragraph in the developer docs for a comparison between Object.assign()
and the spread ...
operator.
Upvotes: 3