When comparing the two constructors:
function C(options, id) {
this.id = id;
// Extend defaults with provided options
this.options = $.extend(true, {}, {
greeting: 'Hello world!',
image: null
}, options);
};
and
function C(params, id) {
this.$ = $(this);
this.id = id;
// Extend defaults with provided options
this.params = $.extend({}, {
taskDescription: '',
solutionLabel: 'Click to see the answer.',
solutionImage: null,
solutionText: ''
}, params);
}
Is the true variable necessary after $.extends?
Secondly, is the statement this.$ = $(this) necessary as the first constructor does not have it and they do the same thing.
The true is necessary if options has any nested objects, if you want to make a deep copy of them rather than having the new objects referring to the same nested objects as the originals.
Simple example:
var inner = {
foo: "bar"
};
var outer = {
inner: inner
};
var shallowCopy = $.extend({}, outer);
var deepCopy = $.extend(true, {}, outer);
console.log(shallowCopy.inner.foo); // "bar"
console.log(deepCopy.inner.foo); // "bar"
outer.inner.foo = "updated";
console.log(shallowCopy.inner.foo); // "updated"
console.log(deepCopy.inner.foo); // "bar"
Live Copy:
var inner = {
foo: "bar"
};
var outer = {
inner: inner
};
var shallowCopy = $.extend({}, outer);
var deepCopy = $.extend(true, {}, outer);
console.log(shallowCopy.inner.foo); // "bar"
console.log(deepCopy.inner.foo); // "bar"
outer.inner.foo = "updated";
console.log(shallowCopy.inner.foo); // "updated"
console.log(deepCopy.inner.foo); // "bar"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
More in the $.extend documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With