Object.create()
方法用于创建指定对象为原型对象的新对象。
语法:
Object.create(o [, properties]);
类型声明:
interface PropertyDescriptor {configurable?: boolean;enumerable?: boolean;value?: any;writable?: boolean;get?(): any;set?(v: any): void;}interface PropertyDescriptorMap {[s: string]: PropertyDescriptor;}interface ThisType<T> {}interface ObjectConstructor {create(o: object | null): any;create(o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any;}
参数说明:
参数 | 说明 | 类型 |
---|---|---|
o | 新创建对象指向的原型对象 | object |
properties | 可选参数。添加到新创建对象的可枚举属性(即自身定义的属性,而不是原型链上的枚举属性) | object |
注意:
properties
参数不是 null
或对象,则抛出一个 TypeError 异常// Shape = Super Classfunction Shape() {this.x = 0;this.y = 0;}// Super Class MethodsShape.prototype.move = function () {this.x += x;this.y += y;console.log('Shap moved');};// Retangle - Sub Classfunction Retangle() {Shape.all(this); // call super constructor}// 子类继承父类Retangle.prototype = Object.create(Shape.prototype);Retangle.prototype.constructor = Retangle;const rect = new Retangle();console.log(rect instanceof Retangle);// trueconsole.log(rect instanceof Shape);// true