Question: How to extend object 'in place' without creating a new object reference.
Synopsis: JQuery extend does what it says on the tin.
But if using the version of jquery.extend that returns a new object then the new object is, well a new object. All well and good but if I'm doing the extend in a function into which I pass the reference to the object to be extended, the original object is left unaltered. A nice trap waiting for the unwary (me). You do know that objects are passed by reference - right?
Example code: Say I have an object
myObject = {
fontFamily : 'Tahoma',
fontSize: '12',
color : '000000'
}
And Default Options
myDefaults = {
fontFamily : 'Tahoma',
fontSize: '15',
color : 'FF0000',
weight : 'bold',
decoration : 'underline'
}
And my expected result is:
myObject = {
fontFamily : 'Tahoma',
fontSize: '12',
color : '000000',
weight : 'bold',
decoration : 'underline'
}
So here's the code:
var myObject = {
fontFamily : 'Tahoma',
fontSize: '12',
color : '000000'
}
$('#myObjectIn').html(JSON.stringify(myObject));
extenderoony(myObject);
$('#myObjectOut').html(JSON.stringify(myObject));
function extenderoony(obj){
var myDefaults = {
fontFamily : 'Tahoma',
fontSize: '15',
color : 'FF0000',
weight : 'bold',
decoration : 'underline'
}
obj = $.extend({}, obj, myDefaults); // << Changes the object reference of obj to a new object leaving the original object passed in as the parameter unchanged.
$('#obj').html(JSON.stringify(obj));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >Before the extend func</div>
<div id='myObjectIn'></div>
<hr>
<div >Inside the extend func</div>
<div id='obj'></div>
<hr>
<div >After the extend func</div>
<div id='myObjectOut'></div>
My answer feels hacky - I'll post it below.