Valentino Langarosa
Valentino Langarosa

Reputation: 307

Backbone or javascript Object extend bug

In comments is output. This is javascript bug, backbone or other?

var t = Backbone.View.extend({
    ben: {},
    banana: function(s){
        this.ben[s] = s;
    },
    show: function(){
        console.info(this.ben)
    }
});
var c1 = new t();
var c2 = new t();
c1.banana('1');
c1.show(); //Object { 1="1"}
c2.banana('2');
c1.show(); //Object { 1="1", 2="2"}

Upvotes: 1

Views: 160

Answers (2)

Rob Hruska
Rob Hruska

Reputation: 120286

The code is behaving as expected (i.e. not a bug). ben is added to the prototype.

Consider doing this instead:

var t = Backbone.View.extend({
    initialize: function (options) {
        this.ben = {};
    }
    banana: function(s){
        this.ben[s] = s;
    },
    show: function(){
        console.info(this.ben)
    }
});

Upvotes: 3

Deleteman
Deleteman

Reputation: 8690

This is not a bug, ben is a "class attribute" (not really because there are no classes in javascript, but it acts like one).

Everytime you do a new t() you're referencing the same ben.

Upvotes: 1

Related Questions