Sam
Sam

Reputation: 2630

Issues with Object.toString in IE8, backbone.js

What is up with IE8 and the toString method of Objects?

I am trying to override toString in my models in Backbone.js, but IE8 doesn't seem to recognize that the method is there. Changing the method name to something else works fine, but why can't I use toString? This works in Chrome.

var Foo = Backbone.Model.extend({
    toString: function(){ return this.get("name"); },
    description: function(){ return this.get("name"); }
});

var f = new Foo({name: "a foo"});

document.writeln(f.toString());    // "[object Object]", should be "a foo"
document.writeln("<br/>");
document.writeln(f.description()); // "a foo"

JSFiddle code: http://jsfiddle.net/x96mR/3/

Upvotes: 6

Views: 2227

Answers (1)

JaredMcAteer
JaredMcAteer

Reputation: 22535

If you move the toString outside the Backbone.Model.extend to:

Foo.prototype.toString = function(){ return this.get("name"); };

It works. I would suspect that Backbone is doing some funky stuff that doesn't work as expected in IE8

Edit (thanks to @Ferdinand Prantl):

All properties passed into the Backbone.extend are added to the model's prototype using for-in enumeration. IE < 9 has a bug where it will not copy certain properties called the DontEnumBug.

DontEnumBug

In IE < 9, JScript will skip over any property in any object where there is a same-named property in the object's prototype chain that has the DontEnum attribute.

constructor, toString, valueOf, toLocaleString, prototype, isPrototypeOf, propertyIsEnumerable, hasOwnProperty, length, and unique will all be skipped.

Upvotes: 9

Related Questions