toString在IE中不起作用 [英] toString does not work in IE
问题描述
我在javascript中有一个定义toString方法的类,但是当我想在页面中打印它时,它总是在IE中打印 [object object]
(6 -8)。
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).
但它适用于firefox或chrome(在下面的示例中它们都打印'kk')。
But it works in firefox or chrome(they all print 'kk' in the example below).
我想知道为什么?
这是示例代码:
function Person(name){
this.name=name;
}
Person.prototype.toString=function(){
return this.name;
}
var p=new Person('kk');
document.getElementById('dis').innerHTML=p.toString();
有什么问题?
BTW,这是我申请中的代码:
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;
截屏:
推荐答案
好的,我现在看到你的问题。
Ok I see your issue now.
在所有旧版本的IE(9之前的版本)中,javascript引擎不允许您修改元素的原型函数。
In all older version of IE (previous to 9) the javascript engine does not let you modify an element's prototype functions.
所以对象的默认 toString()
是 [object Object]
对于旧版本的IE,您可能需要考虑不同的代码方法。
You might have to think of a different approach to your code for older versions of IE.
请参阅此处的文章: http://blog.motane。 lu / 2007/09/20 / elementprototype-in-ie /
.toString
已经预定义的功能在所有对象的原型中,它不能在IE中被覆盖。尝试使用不同的函数名称。
.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.
这篇关于toString在IE中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!