When paring 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.
When paring 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.
-
2
It's necessary when you want the behavior described in the documentation that
true
provides. Andthis.$ = $(this);
is necessary if you want that assignment to take place. None of these things are absolutely required. You need to decide what is needed for your code in each circumstance. – user1106925 Commented Mar 20, 2016 at 16:26
1 Answer
Reset to default 9The 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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
More in the $.extend
documentation.