在javascript中的$ .extend(true,{},obj)中,'true'的目的是什么?

时间:2016-03-20 16:24:24

标签: javascript

比较两个构造函数时:

  function C(options, id) {
    this.id = id;

    // Extend defaults with provided options
    this.options = $.extend(true, {}, {
      greeting: 'Hello world!',
      image: null
    }, options);


  };

  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);
  }

true之后是否需要$.extends变量?

其次,声明this.$ = $(this)是必要的,因为第一个构造函数没有它并且它们做同样的事情。

1 个答案:

答案 0 :(得分:3)

如果true有任何嵌套对象,如果你想对它们进行深层复制而不是让新对象引用与原始文件相同的嵌套对象,则options是必需的。

简单示例:

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"

实时复制:

var inner = {
    foo: "bar"
};
var outer = {
    inner: inner
};
var shallowCopy = $.extend({}, outer);
var deepCopy = $.extend(true, {}, outer);
snippet.log(shallowCopy.inner.foo); // "bar"
snippet.log(deepCopy.inner.foo);    // "bar"
outer.inner.foo = "updated";
snippet.log(shallowCopy.inner.foo); // "updated"
snippet.log(deepCopy.inner.foo);    // "bar"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

More in the $.extend documentation