Object.create(proto, [ propertiesObject ])
参数
-
proto
- 一个对象,应该是新创建的对象的原型。 propertiesObject
-
可选。该参数对象是一组属性与值,该对象的属性名称将是新创建的对象的属性名称,值是属性描述符(这些属性描述符的结构与
Object.defineProperties()
的第二个参数一样)。注意:该参数对象不能是undefined
,另外只有该对象中自身拥有的可枚举的属性才有效,也就是说该对象的原型链上属性是无效的。
抛出异常
如果 proto 参数不是 null
或一个对象值,则抛出一个 TypeError
异常。
例子
使用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(1, 1); //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
};