--- title: Object.prototype.toSource() slug: Web/JavaScript/Reference/Global_Objects/Object/toSource tags: - JavaScript - Method - Object - Prototype translation_of: Web/JavaScript/Reference/Global_Objects/Object/toSource ---
toSource()
方法返回一个表示对象源代码的字符串。
Object.toSource(); obj.toSource()
一个表示对象的源代码的字符串。
toSource()
方法返回以下值:
toSource
返回了下面的字符串,表示源码没法获取:function Object() { [native code] }
toSource()
会返回该实例源代码的字符串表示。在调试时,你可以通过toSource()
来查看一个对象的内容。
允许对象重写toSource()
方法。例如:
function Person(name) { this.name = name; } Person.prototype.toSource = function Person_toSource() { return "new Person(" + uneval(this.name) + ")"; }; alert(new Person("Joe").toSource()); // ---> new Person("Joe")
的toSource方法
每个JavaScript核心类型都有它自己的toSource()
方法.这些对象是:
Math.toSource()
— Returns the String "Math".对于包含对自身的引用的对象 (例如, 循环链表或可以遍历两种方式的树), toSource()
不会重新创建自引用, 如火狐24。例如:
var obj1 = {}; var obj2 = { a: obj1 }; obj1.b = obj2; console.log('Cyclical: ' + (obj1.b.a == obj1)); var objSource = obj1.toSource(); // returns "({b:{a:{}}})" obj1 = eval(objSource); console.log('Cyclical: ' + (obj1.b.a == obj1));
如果使用循环结构, 并且需要 toSource()
, 则对象必须提供对 toSource()
的重写, 无论是对构造函数的引用还是提供匿名函数。
toSource()
下面的代码定义了一个Dog
对象类型还创建了一个Dog
类型的对象实例theDog
:
function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } theDog = new Dog("Gabby", "Lab", "chocolate", "girl");
在theDog
上调用toSource
方法会显示出能定义该对象的源码:
theDog.toSource(); // returns ({name:"Gabby", breed:"Lab", color:"chocolate", sex:"female"})
不属于任何标准的一部分。在JavaScript1.3中实现。
{{Compat("javascript.builtins.Object.toSource")}}