比较两个构造函数时:
function C(options, id) {
this.id = id;
// Extend defaults with provided options
this.options = $.extend(true, {}, {
greeting: 'Hello world!',
image: null
}, options);
};
Run Code Online (Sandbox Code Playgroud)
和
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);
}
Run Code Online (Sandbox Code Playgroud)
true
之后的变量是必需的$.extends
吗?
其次,该语句是否this.$ = $(this)
必要,因为第一个构造函数没有它并且它们做同样的事情。
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"
Run Code Online (Sandbox Code Playgroud)
实时复制:
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"
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)