ToString does not work in IE

I have a class in javascript that defines the toString method, however, when I want to print it on the page, it always prints [object object] in IE (6-8).

But it works in firefox or chrome (they all print "kk" in the example below).

I wonder why?

This is a sample code:

 function Person(name){ this.name=name; } Person.prototype.toString=function(){ return this.name; } var p=new Person('kk'); document.getElementById('dis').innerHTML=p.toString(); 

What is the problem?


By the way, this is the code in my application:

 function inherit(pro) { function F() {}; F.prototype = pro; return new F(); } var Class = function() { var clazz = null, pros = {}; // root of chain for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (typeof arg === "function") { arg = arg.prototype; } else { if (arg.init) { clazz = arg.init; delete arg.init; } var o = arg; arg = (function() { function F() {}; F.prototype = pros; return new F; })(); for (var key in o) arg[key] = o[key]; } pros = arg; } clazz.prototype = pros; return clazz; }; var Person = Class({ init: function(name) { this.name = name; }, toString: function() { return this.name; } }); function init() { var p = new Person('kk'); document.getElementById('dis').innerHTML = p.toString(); } window.onload = init; 

Screenshot:

IE

Firefox

+4
source share
3 answers

Good. Now I see your problem.

In all the old versions of IE (before 9), the javascript mechanism makes it impossible to change the functions of the prototype element.

Thus, the default toString() object [object Object]

You may need to consider a different approach to your code for older versions of IE.

See the article here: http://blog.motane.lu/2007/09/20/elementprototype-in-ie/


The final answer is from the comments below:

.toString already a predefined function in the prototype of all objects, and it cannot be overridden in IE. Try using a different function name.

+1
source

Actually, the above comments are incorrect. Although you may not be able to override the default prototype methods for elements, you can do this for your own types. The problem is that toString is not returned as a key in the code snippet:

 for (var key in o) arg[key] = o[key]; 

if you add the following, everything will work as expected:

 if (o.toString !== Object.prototype.toString) { arg.toString = o.toString } 
+7
source

Actually you can! You just have to move the toString out

 Person.prototype.toString = function() { return this.name; } 

Additional information check this other message

Problems with Object.toString in IE8, backbone.js

0
source

Source: https://habr.com/ru/post/1398609/


All Articles