Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In $.extend(true, {}, obj) in javascript, what is the purpose of 'true'?

Tags:

javascript

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.

like image 631
timothyylim Avatar asked Oct 30 '25 04:10

timothyylim


1 Answers

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.

like image 61
T.J. Crowder Avatar answered Nov 01 '25 19:11

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!