比较两个构造函数时:
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)
是必要的,因为第一个构造函数没有它并且它们做同样的事情。
答案 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>