In JS, Object is very special.

  • JS, everything is an object. Except, of course, null and undefined.
  • Object is a container of properties. Property consists of a name and a value. Name is a string and value can be of any type.

In fact, the definition of object in JS is very broad and brief. For example, the same concept in other languages will include hash table, map, record, dictionary and so on. In JS, the very brief {name: value} already expresses the meaning.

Copy

Object.assign can be used to copy objects. Such as:

const newOject = Object.assign({}, oldObj);
Copy the code

Inheritance

In JS, we can simply make one Object inherit the contents of another Object. It doesn’t need to be implemented through complex class inheritance. Object2 needs to be able to inherit from Object1:

const object2 = Object.create(object1);
Copy the code

Create a new object2 and set object2’s Prototype to Object1.

Const object2 = {}; Object.setPrototypeOf(object2, object1)Copy the code

In fact, in JS, we usually put methods of a certain type in Prototype for specific instances to call. For example, all methods on Array are defined in array. prototype, number and number. prototype.

If Object does not have a property name, check prototype. If not, check prototype’s prototype again.

And since everything is an object, the prototype chain focuses on object.pototype.

Thus, an object has two properties: its property and the prototype property. How do we tell the difference?

We found that the Object. Proptype. HasOwnProperty (string). Since all objects essentially inherit Object.prototype, we can call this method directly on any oobject to check whether a field is the property of the current object. Of course, if hasOwnProperty is not overridden.

You might even need to create an Object with a value of own property. It’s easy, just set Prototype to null.

const newObject = {};
Object.setPrototypeOf(newObject, null)

// OR
const newObject = Object.create(null);
Copy the code

Keys

Keys can get all own property names