非标准
该特性是非标准的,请尽量不要在生产环境中使用它!
概述
返回一个对象源代码的字符串表示.
Method of Object |
|
|---|---|
| Implemented in | JavaScript 1.3 |
| ECMAScript Edition | None |
语法
obj.toSource()
参数
无.
描述
toSource方法返回下面这样的值:
- 对于内置的
Object对象,toSource返回了下面的字符串:
function Object() {
[native code]
}
- 对于
Object的实例,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方法.这些对象有:
- Array.toSource 非标准 - Array对象方法.
- Boolean.toSource 非标准 - Boolean对象方法.
- Date.toSource 非标准 - Date对象方法.
- Function.toSource 非标准 - Function对象方法.
- Number.toSource 非标准 - Number对象方法.
- Object.toSource 非标准 - Object对象方法.
- RegExp.toSource 非标准 - RegExp对象方法.
- String.toSource 非标准 - String对象方法.
例子
例子: 使用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();
返回
({name:"Gabby", breed:"Lab", color:"chocolate", sex:"girl"})