function Point(x, y) {
this.x = x;
this.y = y;
}
var p = new Point(1, 1);
// 不需要传入任何参数给构造函数时,可以省略括号
new Object
new Date
Object.create()
ES 5 定义了Object.create()。
简单示例:
var o1 = Object.create({x : 1, y : 2}); // 创建了o1对象,o1继承了属性x和y
var o2 = Object.create(null); // 创建了o2对象,o2不继承任何属性和方法
var o3 = Object.create(Object.prototype); // 创建了o3对象,o3和{}和new Object()一样
ES 3 中通过如下手段模拟:
function inherit(p) {
if (p === null) throw TypeError();
if (Object.create) return Object.create(p);
var t = typeof p;
if (t !== "object" && t !== "function") throw TypeError();
function f() {
}
f.prototype = p;
return new f();
}
上述中的inherit()有防止库函数无意间修改的作用:
var o = {x : "don't change this value"};
library_function(inherit(o)); // 通过继承时拷贝继承的属性,来避免意外修改了o
序列化对象
对象序列化 是指将对象的状态转换为字符串。
ES 5 提供了JSON.stringify()和JSON.parse()用来 序列化 和 反序列化JavaScript 对象。