The Object constructor creates an Object wrapper.

In JavaScript, almost all objects are instances of type Object, inheriting properties and methods from Object.prototype.

grammar

  1. Object Initialiser or Object literals

    { key1: value1, key2:value2, ... }
    Copy the code
  2. Called as a constructor

    var obj = new Object([value])
    Copy the code

    Depending on the type of the value passed in, the created object has the following situations:

    • The value ofnullundefinedCreates and returns an empty object.
      var o1 = new Object(a)var o2 = new Object(undefined)
      var o3 = new Object(null)
      Copy the code
    • Value is a value of the base data type, and an object of its wrapper type is constructed.
      var bo = new Object(true)
      / / equivalent to the
      var bo = new Boolean(true)
      Copy the code
    • If value is a reference, the value will still be returned, and the value will refer to the same reference address as the original value.

attribute

Object.length

The value is 1.Copy the code

Object.prototype

Prototype a property is an Object type on which attributes can be added to all objects of type Object (whether created before or after).

All objects in JavaScript come from Object, all objects inherit methods and properties from Object.prototype, and changes to Object.prototype are propagated to all objects.

Object. Prototype has the following properties:

Object.prototype.constructor

A prototype used to create an Object that returns a reference to the Object constructor rather than a string containing the function name.

All objects inherit a constructor attribute from their stereotype

var o1 = {}
var o2 = new Object()
o1.constructor === o2.constructor === Object // true

var arr1 = []
var arr2 = new Array()
arr1.constructor === arr2.constructor === Array // true

var n1 = new Object(1)
var n2 = new Number(1)
n1.constructor === n2.constructor === Number // true

var s1 = new Object('s')
var s2 = new String('s')
s1.constructor === s2.constructor === String // true

var b1 = new Object(true)
var b2 = new Boolean(true)
b1.constructor === b2.constructor === Boolean
Copy the code

Object.prototype.hasOwnProperty()

Determines whether an object itself contains a specified property that is not inherited from the stereotype chain.

Grammar: obj. HasOwnProperty (prop)

Object.prototype.isPrototypeOf()

Determines whether an object exists on the prototype chain of another object.

Grammar: prototypeObj isPrototypeOf (Object)

Object.prototype.propertyIsEnumerable()

Determines whether the specified property itself (not inherited through the stereotype chain) is enumerable.

Grammar: obj. PropertyIsEnumerable (prop)

Object.prototype.toLocaleString()

Returns a string representation of an object.

Grammar: obj. ToLocaleString ()

Object.prototype.toString()

Returns a string representation of an object.

Grammar: obj. ToString ()

All objects can be converted to the format of type [object].

Object.prototype.valueOf()

Returns the original value of the specified object.

Grammar: obj. The valueOf ()

If the object has no original value, the object itself is returned.

JavaScript built-in objects almost all override this method, and the corresponding return value is shown in the following table:

object The return value
Boolean Boolean value
Number A numeric value
String string
Array Returns the array object itself
Date The stored event is the number of milliseconds UTC from midnight on January 1, 1970
Object The object itself
Function The function itself

Math and Error objects do not have valueOf methods.

Object.prototype.__proto__

The prototype Object that points to an instance of Object.

methods

Create object methods

Object.assign(target, … sources)?? :

Assigns one or more of the source object’s own enumerable properties to the target object and returns the target object.

If the target object has the same property, the property of the target object is overwritten by the property of the source object, which overwrites the previous property of the source object.

This method uses the [[Get]] of the source object and the [[Set]] of the target object, calling the relevant getters and setters.

Features:

  • Only the string wrapper object has its own enumerable properties and can be wrapped as an object and then copied.
  • Null and undefiend are ignored.
  • When a property is copied again, the reference type only copies the reference, also known as a shallow copy.
  • Exceptions interrupt subsequent copy tasks.

A Polyfill implementation (Symbol not supported) :

if (typeof Object.assign ! = ='function') {
    // Object.assign must be writable, non-enumerable, and configurable
    Object.defineProperty(Object.'assign', {
        value: function assign(target, varArgs) {
            'use strict'
            if (target === null || target === undefined) {
                throw new TypeError('Null and undefined cannot be converted to objects')}var to = Object(target)
            for (var index = 1; index < arguments.length; index++) {
                var nextSource = arguments[index]
                if(nextSource ! = =null&& nextSource ! = =undefined) {
                    for (var nextKey in nextSource) {
                        if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                            to[nextKey] = nextSource[nextKey]
                        }
                    {

                }
            }
            return to
        },
        writable: true.configurable: true})}Copy the code

Copy accessor:

function completeAssign(target, ... sources) {
    sources.forEach(source= > {
        let descriptors = Object.keys(source).reduce((descriptor, key) = > {
            descriptors[key] = Object.getOwnPropertyDescriptor(source, key)
            return descriptors
        })
        // object. assign copies enumerable Symbols by default
        Object.getOwnPropertySymbols(source).forEach(sym= > {
            let descriptor = Object.getOwnPropertyDescriptor(source, sym)
            if (descriptor.enumerable) {
                descriptors[sym] = descriptor
            }
        })
        Object.defineProperties(target, descriptors)
    })
    return target
}
Copy the code

Object.create()

Creates a new object with the specified prototype object and properties.

Syntax: Object.create(proto, [propertiesObject])

Parameter analysis:

  • The first parameter, proto, acts as a prototype object for the new object;
  • The property type of the second argument propertiesObject configures its own enumerable properties to the new Object, including property values and corresponding property descriptors, according to the second argument of Object.defineProperties().

Implement class inheritance:

function Shape(x, y) {
    this.x = 0
    this.y = 0
}
Shape.prototype.move = function(x, y) {
    this.x += x
    this.y += y
}

function Rectangle() {
    super.call(this)
}

Rectangle.prototype = Object.create(Shape.prototype)
Rectangle.prototype.constructor = Rectangle

var rect = new Rectangle()
rect instanceOf Rectangle // true
rect instanceOf Shape // true
Copy the code

Inherit multiple objects:

function MyClass() {
    SuperClass.call(this)
    OtherSuperClass.call(this)}// Inherit a class
MyClass.prototype = Object.create(SuperClass.prototype)
// Mix others
Object.assign(MyClass.prototype, OtherSuperClass.prototype)
// re-specify constructor
MyClass.prototype.constructor = MyClass
Copy the code

How to set/get a property and its configuration

Object.defineProperty()

Adds/modifies a property to an object and specifies the configuration for that property, and returns the object.

Object. DefineProperty (obj, propName, Descriptor)

Parameter analysis:

  • Obj is the object for which attributes are to be defined
  • PropName is the property name or Symbol to define or modify
  • Descriptor Property descriptor to define or modify

What is added via assignment is that ordinary properties are enumerable, and when enumerating object properties are enumerated to for.. In or object. keys, you can change the values of these properties and delete them.

While Object.defineProperty() can modify attribute configuration information, attribute values added by Object.defineProperty() cannot be modified by default.

There are two types of attribute descriptors:

  • Data descriptor: Object type, which is a property with a value that may or may not be writable.
  • Accessor description: Object type, properties described by getter and setter functions.

Both descriptors have the following two optional attributes:

  • Different: the default is false. If and only if the value is true, the descriptor of the property can be changed and the property can be deleted from the corresponding object.
  • Enumerable: Default false. This property appears in the enumeration property of the object if and only if the value is true.

The data descriptor also has the following two optional attributes:

  • Writable: default false. The attribute’s value assignment operator changes only if and only if the value is true.
  • Value: Attribute value, undefined by default. Can be any valid JavaScript value.

Accessor descriptors also have the following two optional attributes:

  • Get: The getter function for the property, undefined by default. This function is called when a property is accessed. No arguments are passed, but this object is passed (because of inheritance, this is not necessarily the object that defines the property). The return value of this function is used as the value of the property.
  • Set: the setter function for the property, undefined by default. This function is called when the value of an attribute is modified. This method takes a parameter (also the new value assigned) and passes in the this object at the time of assignment.

Remark:

  • Descriptor properties are not necessarily their own properties, but can also be inherited properties.
  • You should call Object.defineProperty() directly instead of calling the defineProperty() method of an instance of Object.
  • In ES6, Object.defineProperty() is one of the ways to define a key of type Symbol.

Object.defineProperties()

Add multiple properties to an object and specify their configuration separately.

Object.getOwnPropertyDescriptor()

Returns the property configuration specified by the object.

Methods to get object properties and property values

Object.entries()

Returns a [key, value] array of the given object’s own enumerable properties.

Object.keys(arg)

Returns an array of strings containing the (non-inherited) enumerable property names of the given object itself.

Return the order of the elements of the array and for… The sequence of the in loop is the same, and the output is in ascending order.

In ES5, TypeError is raised if arG is not an object (primitive value). In ES, non-object arguments are cast to the object in the call. for… In traverses the enumerable properties of an object, containing inherited enumerable properties.

Object. Keys () Polyfill

if (!Object.keys) {
    Object.keys = (function() {
        var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumbBug = ! ({toString: null}).propertyIsEnumerable('toString'),
            dontEnums = [
                'toString'.'toLocaleString'.'valueOf'.'hasOwnProperty'.'isPrototypeOf'.'propertyIsEnumerable'.'constructor'
            ],
            dontEnumsLength = dontEnums.length

        return function (obj) {
            if (typeofobj ! = ='object' && typeofobj ! = ='function' || obj === null) throw new TypeError('Call object.keys on non-objects')

            var result = []
            for (var prop in obj) {
                if (hasOwnProperty.call(obj, prop)) {
                    result.push(prop)
                }
            }

            // If there is an enumeration property bug, output the non-enumerable property as well
            if (hasDontEnumbBug) {
                for (var i = 0; i < dontEnumsLength; i++) {
                    if (hasOwnProperty.call(obj, dontEnums[i])) {
                        result.push(dontEnums[i])
                    }
                }
            }
            return result
        }

    })
}
Copy the code

Object.values()

Returns an array containing the enumerable property values of the given object itself (not inherited), the order of the array elements, and for… The order of the in cycle is the same.

When a non-object parameter is passed in, it is cast to an object and then called.

Object.values(' ABC ') // Return ['a', 'b', 'c']Copy the code

When the class array is passed, and the class array’s key value is a numeric type, when the generated array elements are printed in ascending order by the numeric key.

Object. Values ({2: 'aa', 1: 'bb', 3: 'cc'} / / return [' bb ', 'aa', 'cc']Copy the code

Object. Values () Polyfill:

if (!Object.values) {
    Object.values = function(obj) {
        if(obj ! = =Object(obj)) {
            throw new TypeError('Please pass in an object parameter')}var values = [], key
        for (key in obj) {
            if(Object.prototype.hasOwnProperty.call(obj, key)) {
                values.push(obj[key])
            }
        }
        return values
    }
}
Copy the code

Object.getOwnPropertyNames()

Returns an array containing the names of all enumerable and non-enumerable properties of the specified object.

Object.getOwnPropertySymbols()

Returns an array containing all the Symbol properties of the specified object itself.

Object is not available

Object.freeze()

Freeze the object, and no other code can delete or change any properties.

Object.isFrozen()

Checks whether the object is frozen.

Object.isExtensible()

Determines whether an object is extensible.

Object.isSealed()

Check whether the object is sealed.

Object.preventExtensions()

Prevents any extension of the object.

Object.seal()

Prevents other code from deleting attributes of the object.

Methods for prototyping objects

Object.getPrototypeOf()

Returns the prototype object of the specified object.

Object.setPrototypeOf()

Sets the prototype of the object (that is, the prototype property of the object).

Method of comparison

Object.is()

Compare whether two values are the same, and all NaN values are equal.