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/
toString() ). This method is inherited by every object descended from Object , but can be overridden by descendant objects (for example, Number. prototype. 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With