Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default values are passed in by reference #1145

Closed
nagyv opened this issue Mar 26, 2012 · 4 comments
Closed

Default values are passed in by reference #1145

nagyv opened this issue Mar 26, 2012 · 4 comments
Labels

Comments

@nagyv
Copy link

nagyv commented Mar 26, 2012

Having an empty array as a default value can definitely trick the user:

http://jsfiddle.net/bika/Kn5sP/2/

Is this intended?

@tbranyen
Copy link
Collaborator

"Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances."

http://backbonejs.org/#Model-defaults

This is expected behavior, you can use a function for defaults and return an object that contains a reference type.

defaults: function() {
  return {
    shared: []
  };
}

@braddunbar
Copy link
Collaborator

Yes, this is intentional. For different behavior defaults can be provided as a function. Please see #476 for more information.

@Benjen
Copy link

Benjen commented Apr 4, 2012

I was struggling with this until I can across this issue here. Perhaps it would be beneficial to update the documentation to explain this slightly. Currently it reads:

"Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances."

Perhaps we could change it to:

"Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances. Defaults containing objects passed by reference should be defined using a function if you do not wish to share objects between all instances."

@braddunbar
Copy link
Collaborator

@Benjen That sounds reasonable to me. Care to work up a pull request to that effect?

Benjen pushed a commit to Benjen/backbone that referenced this issue Apr 5, 2012
…n, to explain when to use a function to define model default values. See Issue jashkenas#1145
jashkenas added a commit that referenced this issue Apr 9, 2012
Issue #1145: Changed documentation to elaborate when to use a function to define model defaults.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants