toString does not work in IE

久未见 提交于 2019-12-10 17:52:12

问题


I have a class in javascript which define the toString method,however when I want to print it in the page,it always print [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 the example 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?


BTW,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;

Screen shot:


回答1:


Ok I see your issue now.

In all older version of IE (previous to 9) the javascript engine does not let you modify an element's prototype functions.

So the default toString() of an object is [object Object]

You might have to think of a different approach to your code for older versions of IE.

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


Final answer from comments below:

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




回答2:


Actually the comments above are not correct. Although you may not be able to override default prototype methods on elements, you CAN do it 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, things will work as expected:

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



回答3:


Actually you can! You just gotta move the toString outside

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

Further info check this other post

Issues with Object.toString in IE8, backbone.js



来源:https://stackoverflow.com/questions/9466156/tostring-does-not-work-in-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!