The short answer
When you call extends
to define your object, you are passing the new object's configuration in as an object literal. Objects are passed by reference, and the extends
function only passes a reference to the tags array in to the new type definition.
As noted by others, you can correct this by assigning tags
to a function. This works because a function delays the evaluation of the tags
until the object is instantiated. There's nothing native in JavaScript that does this, but it's Backbone itself that recognizes tags
as a function or a value.
The long answer
In spite of your code being in CoffeeScript, this comes down to a combination of a few things in JavaScript:
- There are no classes in JavaScript
- Object literals are evaluated immediately
- JavaScript objects are passed around by reference
In JavaScript, there are no classes. Period. CoffeeScript gives you the notion of a class, but in reality, it gets compiled down to JavaScript which has no classes.
You can have types and type definitions (constructor functions) but not classes. Backbone provides a class-like definition, that looks similar to Java's "extend" class-based inheritance. It's still just JavaScript, though, which has no classes.
What we have, instead, is an object literal being passed in to the extends
method. It's as if you write this code:
var config = {
tags: []
}
var MyModel = Backbone.Model.extends(config);
In this code, config
is an object literal, or a hash, or a key/value pair, or an associative array. Whatever name you call it, it's the same basic idea. You end up with a config
object that has a tags
attribute. The value of config.tags
is an empty array, []
, which is itself an object.
Which brings us back to the short answer:
When you call extends
to define your object, you are passing the new object's configuration in as an object literal. Objects are passed by reference, and the extends
function only passes a reference to the tags array in to the new type definition.
As noted by others, you can correct this by assigning tags
to a function. This works because a function delays the evaluation of the tags
until the object is instantiated. There's nothing native in JavaScript that does this, but it's Backbone itself that recognizes tags
as a function or a value.