Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 787
Sam Avatar asked Jul 25 '11 19:07

Sam


People also ask

Can we override toString method in JavaScript?

toString() ). This method is inherited by every object descended from Object , but can be overridden by descendant objects (for example, Number. prototype. toString() ).

Do all JavaScript objects have toString?

Every JavaScript object has a toString() method. The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.

How many parameters are required for toString in JavaScript?

Parameters Used: This method accepts a single optional parameter base. This parameter specifies the base in which the integer is represented in the string. It is an integer between 2 and 36 which is used to specify the base for representing numeric values.

What is object toString JavaScript?

JavaScript Object toString() The toString() method returns an object as a string. The toString() method returns "[object Object]" if it cannot return a string. Object. toString() always returns the object constructor.


1 Answers

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.

like image 100
JaredMcAteer Avatar answered Sep 19 '22 21:09

JaredMcAteer