概述
创建一个拥有指定原型和若干个指定属性的对象.
Method of Object |
|
---|---|
Implemented in | JavaScript 1.8.5 |
ECMAScript Edition | ECMAScript 5th Edition |
语法
Object.create(proto [, propertiesObject ])
参数
- proto
- 一个对象,作为新创建对象的原型.
- propertiesObject
- 一个对象值,可以包含若干个属性,属性名为新建对象的属性名,属性值为那个属性的属性描述符对象.
描述
如果proto参数的值不是null或者对象值,则会TypeError
异常.
例子
使用Object.create
var o; // 创建一个原型为null的空对象 o = Object.create(null); o = {}; // 以字面量方式创建的空对象就相当于: o = Object.create(Object.prototype); o = Object.create(Object.prototype, { // foo会成为所创建对象的数据属性 foo: { writable:true, configurable:true, value: "hello" }, // bar会成为所创建对象的访问器属性 bar: { configurable: false, get: function() { return 10 }, set: function(value) { console.log("Setting `o.bar` to", value) } }}) function Constructor(){} o = new Constructor(); // 上面的一句就相当于: o = Object.create(Constructor.prototype); // 当然,如果在Constructor函数中有一些初始化代码,Object.create不能执行那些代码 // 创建一个以另一个空对象为原型,且拥有一个属性p的对象 o = Object.create({}, { p: { value: 42 } }) // 省略了的属性特性默认为false,所以属性p是不可写,不可枚举,不可配置的: o.p = 24 o.p //42 o.q = 12 for (var prop in o) { console.log(prop) } //"q" delete o.p //false //创建一个可写的,可枚举的,可配置的属性p o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });
使用Object.create实现原型继承
下面的例子演示了如何使用Object.create来实现单继承.
//Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); //call super constructor.
}
Rectangle.prototype = Object.create(Shape.prototype);
var rect = new Rectangle();
rect instanceof Rectangle //true.
rect instanceof Shape //true.
rect.move(); //Outputs, "Shape moved."
如果你希望能继承到多个对象,则可以使用混入的方式.
function MyClass() {
SuperClass.call(this);
OtherSuperClass.call(this);
}
MyClass.prototype = Object.create(SuperClass.prototype); //inherit
mixin(MyClass.prototype, OtherSuperClass.prototype); //mixin
MyClass.prototype.myMethod = function() {
// do a thing
};
mixin函数会把超类原型上的函数拷贝到子类原型上,这里mixin函数没有给出,需要由你实现.
浏览器兼容性
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 5 | {{ CompatGeckoDesktop("2") }} | 9 | 11.60 | 5 |
Feature | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | {{ CompatGeckoDesktop("2") }} | {{ CompatVersionUnknown() }} | {{ CompatUnknown() }} | 11.50 | {{ CompatVersionUnknown() }} |
Polyfill
if (!Object.create) { Object.create = function (o) { if (arguments.length > 1) { throw new Error('Object.create implementation only accepts the first parameter.'); } function F() {} F.prototype = o; return new F(); }; }
这个polyfill只实现了创建一个指定原型的对象的功能,而不能同时添加特定的属性,也就是没有实现原生的Object.create函数中的第二个参数.
相关链接
Object.defineProperty
- Object.defineProperties
- Object.prototype.isPrototypeOf
- John Resig's post on getPrototypeOf