50 lines
1.2 KiB
Plaintext
50 lines
1.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
When using the Backbone.js framework with model ``++defaults++`` that contain arrays or objects, ``++defaults++`` should be defined as a function rather than an object. This is because objects and arrays are passed by reference in JavaScript. So a ``++defaults++`` object that contains arrays or objects is going to set the default value of every instance to point to the same shared object or array.
|
|
|
|
|
|
Use a function instead and a fresh copy of the object or array will be peeled off for each instance.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,javascript]
|
|
----
|
|
var Person = Backbone.Model.extend({
|
|
defaults: { // Noncompliant; every instance of Person will share the same instance of favoriteColors
|
|
favoriteColors: ["blue","purple","raspberry"]
|
|
}
|
|
});
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,javascript]
|
|
----
|
|
var Person = Backbone.Model.extend({
|
|
defaults: function() {
|
|
return {
|
|
favoriteColors: ["blue","purple","raspberry"]
|
|
};
|
|
}
|
|
});
|
|
----
|
|
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|