The Copied Object Does Not Inherit Getter or Setter from the Origianal Object in JavaScript
When we copy an object using the three-dot operator, the setter and the getter of the object are not copied.
the getter's initial value of be copied over to the new object as just its property and the setter will be undefined.
var obj_1 = {
count:1,
price:100,
get total(){
return this.count * this.price
},
set priceSetter(value){
this.price = value;
}
}
var objCopy_1 = {...obj_1};
console.log(objCopy_1);
//{count: 1, price: 100, total: 100, priceSetter: undefined}
Playground
Count:<input oninput="obj_1.count = this.value;show_1.innerHTML = obj_1.total;" type="number" value="1" />
<div>The total is <span id="show_1"></span></div>
Count:<input oninput="objCopy_1.count = this.value;show_2.innerHTML = objCopy_1.total;" type="number" value="1" />
<div>The total is <span id="show_2"></span></div>
<script>
var obj_1 = {
count:1,
price:100,
get total(){
return this.count * this.price
},
set priceSetter(value){
this.price = value;
}
}
var objCopy_1 = {...obj_1};
</script>
Count:
The total is
Count:
The total is
The Object Methods Are Copied Over to the New One
Count:<input oninput="obj_2.count = this.value;show_3.innerHTML = obj_2.total();" type="number" value="1" />
<div>The total is <span id="show_3"></span></div>
Count:<input oninput="objCopy_2.count = this.value;show_4.innerHTML = objCopy_2.total();" type="number" value="1" />
<div>The total is <span id="show_4"></span></div>
<script>
var obj_2= {
count:1,
price:100,
total:function(){
return this.count * this.price;
}
}
var objCopy_2 = {...obj_2};
</script>
Count:
The total is
Count:
The total is
Comments
Post a Comment