js create object object.create() usage

The Object.create() method is a new method in ECMAScript 5. This method is used to create a new object. The object being created inherits the prototype of another object, and some properties can be specified when creating a new object.

Syntax: Object.create(proto[,propertiesObject]) proto:  object, the prototype to inherit propertiesObject: object, optional parameter, specify the property object for the newly created object. The properties object may contain the following values: 
 
 

Attributes illustrate
configurable Indicates whether the newly created object is configurable, that is, whether the properties of the object can be deleted or modified, the default is false
enumerable Whether the object property is enumerable, that is, whether it can be enumerated, the default is false
writable Whether the object is writable, or whether to add new properties to the object, default false
get Object getter function, default undefined
set Object setter function, default undefined

Note that when using the Object.create() method to create an object, if you create a brand new object instead of inheriting an original object, you must set proto to null.

Let's look at a simple application

// 基类
function Site() {
  this.name = 'Site';
  this.domain = 'domain';
}

Site.prototype.create = function(name, domain) {
  this.name = name;
  this.domain = domain;
};

// 子类
function Itbilu() {
  Site.call( this ); // call the base class constructor 
}

// Inherit the parent class 
Itbilu.prototype = Object.create(Site.prototype);

// Create a class instance 
var itbilu = new Itbilu();

itbilu instanceof Site;  // true
tbilu instanceof Itbilu;  // true

itbilu.create('IT笔录', 'itbilu.com');
itbilu.name;     // 'IT Biography' 
itbilu.domain;   // 'itbilu.com'

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324683434&siteId=291194637