I am creating a BackBone JS application that includes inheriting and using instanceof javascript keyword.
I have the following code:
app.Sport = Backbone.Model.extend ({ defaults: { id: 0, title: 'Running' } });
Further in the code I create a new Sport by typing:
var newSport = new app.Sport ();
I can manipulate this newly created instance without problems.
But, as there is, but the instanceof keyword always returns false when prompted for the type of my instance:
console.log ('is newSport a Sport instance ? ' + newSport instanceof app.Sport);
false is always displayed. Why?
Note. I did not mention the inheritance in my question, since it does not even work with a simple OOP form (one instance of a base class and a type request right away).
My initial goal is to initiate a specific action depending on the type of sport (thus using the instanceof keyword); It can be cool or extreme:
app.CoolSport = app.Sport.extend ({ ... }); app.ExtremeSport = app.Sport.extend ({ ... });
EDIT . I highlighted the problem. It is not associated with an instanceof keyword or a declared model. Rather, I fill out the Backbone collection and push various sports to it. Here is the test code: ( Fiddle )
var app = {}; app.Sport = Backbone.Model.extend ({ defaults: { id: 0, title: 'Running' } }); app.CoolSport = app.Sport.extend ({ defaults: { uselessAttr:'I am a Cool Sport !' } }); app.SportList = Backbone.Collection.extend ({ model: app.Sport }); var coolSport1 = new app.CoolSport(); console.log ('is coolSport1 a Sport instance ? ' , coolSport1 instanceof app.Sport); console.log ('is coolSport1 a CoolSport instance ? ' , coolSport1 instanceof app.CoolSport); console.log ('is coolSport1 a CoolSport instance (wrong operand in console) ? ' + coolSport1 instanceof app.CoolSport); var sportList = new app.SportList(); sportList.push (coolSport1.toJSON()); sportList.each ( function ( sport ) { if ( sport instanceof app.CoolSport ) { console.log ( "sport is an instance of Cool Sport ! Yeah !" , sport instanceof app.CoolSport ) ; } else { console.log ( "Not a CoolSport instance.."); } });
And guess what? my CoolSport instance ... is not a CoolSport instance. I suspect a build issue of the Backbone SportList is a problem.
Any ideas?