非标准
该特性是非标准的,请尽量不要在生产环境中使用它!
toSource()方法返回一个表示对象源代码的字符串。
语法
Object.toSource(); obj.toSource()
返回值
一个表示对象的源代码的字符串。
描述
toSource()方法返回以下值:
- 对于内置的
Object对象,toSource返回了下面的字符串,表示源码没法获取:
function Object() {
[native code]
}
- 对于
Object的实例,toSource()会返回该实例源代码的字符串表示。
在调试时,你可以通过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()方法.这些对象是:
Arrayobject.Booleanobject.Dateobject.Functionobject.Numberobject.RegExpobject.SIMDobjects.Stringobject.Symbolobject.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中实现。
浏览器兼容
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toSource
|
Chrome No support No | Edge No support No | Firefox Full support 1 | IE No support No | Opera No support No | Safari No support No | WebView Android No support No | Chrome Android No support No | Firefox Android Full support 4 | Opera Android No support No | Safari iOS No support No | Samsung Internet Android No support No | nodejs No support No |
Legend
- Full support
- Full support
- No support
- No support
- Non-standard. Expect poor cross-browser support.
- Non-standard. Expect poor cross-browser support.
- Deprecated. Not for use in new websites.
- Deprecated. Not for use in new websites.