Javascript toSource()方法不起作用

时间:2009-07-09 02:40:59

标签: javascript

我收到“对象不支持此属性或方法错误”,有人知道为什么吗?

我的值已插入userId,fname,lname,oname,sam,hasAccess

function Employee(id, fname, lname, oname, sam, access) {
    this.id = id;
    this.fname = fname;
    this.lname = lname;
    this.oname = oname
    this.sam = sam;
    this.access = access;
}

var emp = new Employee(userId, fname, lname, oname, sam, hasAccess);

var jsonstuff = emp.toSource(); //Breaking here

虽然此链接表示可能http://www.w3schools.com/jsref/jsref_toSource_date.asp

5 个答案:

答案 0 :(得分:22)

toSource()在Internet Explorer或Safari中无效。它只是Gecko。有关替代方案,请参阅Implementing Mozilla's toSource() method in Internet Explorer

答案 1 :(得分:9)

请尝试使用JSON serializertoSource是Mozilla特有的,IE不支持。

如果你只是调试那么你最好的选择是install Firebug并使用console.dir(emp);将对象的内容打印到控制台窗口。

更新:请注意,它在link you posted上说“注意:此方法在Internet Explorer中不起作用!”并在MDC page上标明“非标准”。

答案 2 :(得分:5)

你可以改为调用toString,或者放入这样的条件......

var jsonstuff = (emp.toSource) ? emp.toSource() : emp.toString();

修改

由于这不适合您,您可能需要使用JSON.stringify()

答案 3 :(得分:3)

虽然不推荐(扩展本机JS对象),但在开发期间您可以使用:

Object.prototype.toSource 
    || (Object.prototype.toSource = function(){return JSON.stringify(this);})

c = {a:100}
//>Object
c.toSource()
//>"{"a":100}"

喝彩!

答案 4 :(得分:1)