Objects are unordered collections of attributes.

create

  1. Use object direct quantities
var obj = {}
Copy the code
  1. Create (constructor) with new
var obj = new Object(a);var arr = new Array(a);Copy the code
  1. Create (ES6) with object.create ()

The object.create (Prototype Object, custom (non-enumerable) property Object) method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object

var tempObj = {
  x: 1.y: 2
}
var newAttrObj = {
  a: {
    writable: true.configurable: true.value: 100}}var obj = Object.create(tempObj, newAttrObj);
console.log(obj);
/ / {
// a: 100,
// __proto__: {
// x: 1,
// y: 2
/ /}
// }
Copy the code

Create a plain empty object

var obj3 = Object.create(Object.prototype);
obj3.toString(); // [object Object]
Copy the code

Creates an empty object that does not inherit any properties or methods

var obj2 = Object.create(null);
obj2.toString(); // TypeError: obj2.toString is not a function
Copy the code

Attribute query and setting

  1. through.To access or assign a value
var obj = {x:1}
obj.x; / / 1
obj.y = 2;
Copy the code
  1. through[]To access or assign a value
var obj = {y:2}
obj[y]; / / 2
obj[x] = 1;
Copy the code

The difference between:

methods On the right side Whether the right side can be a number/variable/dash
. A simple identifier named “Property Name” N
[] An expression that evaluates to “string” Y
var obj = {name: 'jack'.12: 'Hahaha'.'old-price': 188};
obj[12]; / / ha ha ha
obj12.; // SyntaxError: Unexpected number
obj['old-price']; / / 188
obj.old-price; // ReferenceError: price is not defined

var attrName = 'name';
obj[attrName]; // jack
obj.attrName; // undefined
Copy the code

Attribute types

An object attribute consists of a name, value, and a set of attributes. In ECMAScript5, property values can be replaced with one or two methods, getters and setters. Properties defined by getters and setters are called accessor properties, or accessor properties.

Each property of an object has a Descriptor that controls the behavior of the property.

There are two types of properties in ECMAScript: data properties and accessor properties.

Data attributes

A data attribute contains the location of a data value. Values can be read and written from this location. Data attributes have four properties that describe their behavior, also known as attribute properties.

The property name instructions The default value
configurable An attribute can be redefined by deleting it through DELETE, its properties can be modified, or an attribute can be changed to an accessor attribute true
enumerable Whether a for-in loop can be used to return properties true
writable Whether the value of an attribute can be modified true
value Property data values, property values are stored and read in this location undefined

1. Can passObject.getOwnPropertyDescriptor()View the description object of the property

Use: Object. GetOwnPropertyDescriptor (attribute Object, attribute name)

let obj = { foo: 123 };
Object.getOwnPropertyDescriptor(obj, 'foo')
//  {
// configurable: true
// enumerable: true
// value: 123
// writable: true
/ /}
Copy the code

2. Can passObject.defineProperty()Modify the default properties

Use: object.defineProperty (attribute Object, attribute name, descriptor Object)

var person = {}; 
Object.defineProperty(person, "name", { 
  configurable: false.writable: false.value: "Nicholas" 
}); 
console.log(person.name); //"Nicholas"

person.name = "Greg"; 
console.log(person.name); //"Nicholas" => Writable is false and the modification is invalid

delete person.name;
console.log(person.name); //"Nicholas" => signals is false, and deletion is invalid.Copy the code

Note:

  1. useObject.defineProperty()Define a new property describing the property of the object with a default value of false.
var person = {
  age: 10
}; 
Object.defineProperty(person, "name", {
  value: "Nicholas" 
}); 
Object.getOwnPropertyDescriptor(person, 'name')

// A new property describing the object's property is false by default
/ / {
// configurable: false
// enumerable: false
// value: "Nicholas"
// writable: false
// }


Object.defineProperty(person, "age", {
  value: "30".configurable: false
}); 
Object.getOwnPropertyDescriptor(person, 'age')
// Existing attributes only affect the set attributes
/ / {
// configurable: false
// enumerable: true
// value: "30"
// writable: true
// }

Copy the code
  1. Once a property is defined as unconfigurable, it cannot be changed back to configurable. Calling object.defineProperty () to modify features other than writable will result in an error.
var person = {}; 
Object.defineProperty(person, "name", { 
 configurable: false.value: "Nicholas" 
}); 
// Throw an error
Object.defineProperty(person, "name", { 
 configurable: true.value: "Nicholas" 
});
Copy the code

Access getter and setter properties

Accessor properties do not contain data values; They contain a pair of getter and setter functions (neither, however, is required).

  • When the accessor property is read, the getter function is called, which returns a valid value;
  • When an accessor property is written, a setter function is called and a new value is passed in. This function is responsible for deciding how to process the data.

The accessor property has the following four properties.

The property name instructions The default value
configurable An attribute can be redefined by deleting it through DELETE, its properties can be modified, or an attribute can be changed to an accessor attribute true
enumerable Whether a for-in loop can be used to return properties true
get The function that is called when a property is read. Only get is a read-only property undefined
set The function that is called when a property is written. Set alone is a write-only property undefined

Note: Accessor properties cannot be defined directly and must be defined using Object.defineProperty()

  1. useObject.defineProperty()Defining individual attributes
var book = { 
  _year: 2018.edition: 1 
}; 
Object.defineProperty(book, "year", { 
  get: function(){ 
    return this._year; 
  }, 
  set: function(newValue){
    if (newValue > 2004) { 
      this._year = newValue; 
      this.edition += newValue - 2018; }}}); book.year =2020; // year: 2020
book.edition; / / 3
Copy the code
  1. useObject.defineProperties()Defining multiple properties
var book = {}; 
Object.defineProperties(book, { 
    _year: { // Data attributes
        value: 2018 
    }, 
    edition: { // Data attributes
          value: 1 
    },
    year: { Accessor properties
        get: function(){
            return this._year; 
        }, 
        set: function(newValue){ 
            if (newValue > 2018) { 
                this._year = newValue; 
                this.edition += newValue - 2018; }}}});Copy the code

Application scenarios

“Javascript Property Type Application Scenarios”

conclusion

  • Data attributes are inherent to attributes and can be inherited
  • Accessor properties are created and can be inherited

Related methods:

methods role instructions
Object.getOwnPropertyDescriptor() Property to describe the object
Object.defineProperty() Modify properties default properties/define individual properties Both the data attribute and accessor attribute are available, and the default value of the data attribute is false
Object.defineProperties() Defining multiple properties The data attribute and accessor attribute are available, but the data attribute cannot be set to true when set to false

Delete the properties

The delete operator deletes an object property and returns a Boolean value (true on success, false otherwise).

Grammar:

  • delete object.property
  • delete object['property']

Deleting object Properties

var obj = {x:1}
delete obj.x; // true
Copy the code

Removes an array element, but the array length is not affected

var arr = ['jack'.'tony'.'jenny']
delete arr[1];
console.log(arr); // ['jack', empty, 'jenny']
console.log(arr[1]); // undefined
console.log(arr.length); / / 3

Copy the code

Note:

  • The delete attribute does not exist, delete will not work, but will still return true
  • Delete can only delete its own attributes, not the stereotype attributes, unless it is deleted from the stereotype
  • The non-configurable property of the system cannot be removed
  • Unable to delete any properties declared using var (including global and function scope)
  • Property declared by let/const cannot be deleted
/** * The delete attribute does not exist, delete will not work, but will still return true **/
var obj = {x:1}
delete obj.y; // true

/** * delete can delete only its own attributes, but cannot delete stereotype attributes unless */ is deleted from the stereotype
function Foo() {
  this.bar = 10;
}
Foo.prototype.bar = 42;
var foo = new Foo();
delete foo.bar; // true, because the object itself is being deleted
console.log(foo.bar); // 42, foo.bar is still available because it is available on the prototype chain.
// Remove attributes from the stereotype
delete Foo.prototype.bar; // true
// Since the "bar" attribute has been removed, it can no longer be inherited from Foo.
console.log(foo.bar);  //undefined

/** * The non-configurable property cannot be removed */
var Employee = {};
Object.defineProperty(Employee, 'name', {configurable: false});
console.log(delete Employee.name); // false

/** * cannot delete any attributes declared with var */
var ss = 100;
delete ss; // false
window.ss; / / 100
console.log(Object.getOwnPropertyDescriptor(window.'ss')); 
// {configurable: false, enumerable: true, value:100,writable: true}

/** * cannot delete the property declared by let/const */

let name = 'jack';
const age = '10';
console.log(Object.getOwnPropertyDescriptor(this.'name'))
// {configurable: false, enumerable: true}
console.log(delete name); // false
console.log(delete age); // false
console.log(name, age) // 'jack' 10
Copy the code

Test attributes

Checks whether a property exists in an object. JavaScript Basics – Data Types

  1. in

Can detect owned and inherited properties, and returns true if contained.

var o = {x: 1.k: undefined}
"x" in o; // true - own attribute
"k" in o; // true - own attribute
"y" in o; // false - Non-o object properties
"toString" in o; // true - inherits attributes
Copy the code
  1. hasOwnProperty()

Can detect its own properties, including returns true. Returns false if it is an inherited property.

var o = {x: 1.k: undefined};
o.hasOwnProperty("x"); // true - own attribute
o.hasOwnProperty("k"); // true - own attribute
o.hasOwnProperty("y"); // false - Non-o object properties
o.hasOwnProperty("toString"); // false - inherits attributes
Copy the code
  1. propertyIsEnumerable()

An enhanced version of hasOwnpreperty() that returns true only if it detects that it has a property of its own and that the property’s enumerability is true.

var o = {x: 1}
// todo, output x can be held
o.propertyIsEnumerable("x"); // true - Has its own attributes, which are enumerable
// todo sets y, and y is enumerable false
o.propertyIsEnumerable("y"); // false - Non-o object properties
o.propertyIsEnumerable("toString"); // false - inherits attributes
Copy the code
  1. Use! = =

Through! == Checks whether an attribute is undefined. If the attribute value is undefined, it cannot be detected

var o = {x: 1.k: undefined} o.x ! = =undefined; // true - own attributeo.y ! = =undefined; // false - Non-o object propertieso.toString ! = =undefined; // true - inherits attributeso.k ! = =undefined; // false - If the attribute value is undefined, it cannot be detected
Copy the code

contrast

methods Detect own properties Detect inheritance properties The property whose detection value is undefined Checks for enumerability of properties
in Y Y Y N
hasOwnProperty() Y N Y N
propertyIsEnumerable() Y N ? Y
! = = Y Y N N

Intrinsic properties

Each object has three properties: Prototype, class and Extensible.

1. Prototype Attributes

The stereotype properties of an object are used to inherit properties, which are also referred to as stereotypes.

Prototype chain

When it comes to inheritance, JavaScript has only one structure: objects. Each instance object has a private attribute (called __proto__) that points to its constructor’s prototype object, i.e. The prototype object also has a prototype object of its own (PROTO), cascading up until an object’s prototype object is null. Null, by definition, has no prototype and serves as the last link in the prototype chain.

Use different methods to create objects, the search for the prototype chain is different, see “Inheritance and prototype chain” for details.

__proto__The relation and difference with Prototype

In all implementations, there is no way for an object instance to access the prototype through [[prototype]], so __proto__ is defined to refer to the prototype of the object constructor

  • Prototype is the prototype property of an object and can be inherited
  • __proto__ Prototype to point to the object constructor
  • The constructor property points the prototype object to the associated constructor

function Person() {};

var p1= new Person();
var p2 = new Person();

typeof Person; // function
typeof p1; // object

p1.prototype; // undefined => Instance object has no prototype attribute
Object.getPrototypeOf(p1) == Person.prototype; // true => p1's prototype object is Person's prototype object
p1.constructor == Person; // true => p1's constructor points to the associated constructor
Person.prototype.constructor == Person; // true => the constructor property points the prototype object to the associated constructor

p1.__proto__ === p2.__proto__; // true

p1.__proto__ === p1.constructor.prototype; // true
p1.__proto__ === Person.prototype; // true
p1.constructor.prototype === Person.prototype; // true

Person.__proto__ == Person.constructor.prototype; // true
Person.__proto__ == Object.constructor.prototype // true
Person.constructor.prototype == Object.constructor.prototype // true

Object.__proto__ == Object.constructor.prototype // true

// The literal method is created
var a = {}

a.__proto__ == a.constructor.prototype; // true
a.__proto__ == Object.prototype; // true
Copy the code

Proto_ proto_ and prototype

isPrototypeOf()

IsPrototypeOf () : Tests whether an object exists on another object’s prototype chain

function Foo() {}
function Bar() {}
function Baz() {}

Bar.prototype = Object.create(Foo.prototype);
Baz.prototype = Object.create(Bar.prototype);

var baz = new Baz();

console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true
Copy the code

2. The class attribute

A class attribute of an object is a string that represents the type information of the object. It can be queried using the toString() method. The default toString() method returns a string of the following format:

[object class]

The toString() method can be overridden, so you need to call the function.call () method indirectly to get the correct data

function classof(o) {
  return Object.prototype.toString.call(o);
  // return Object.prototype.toString.call(o).slice(8, -1);
}

classof(null);         // [object Null]
classof(undefined);    // [object Undefined]
classof(1);            // [object Number]
classof("");           // [object String]
classof(false);        // [object Boolean]
classof({});           // [object Object]
classof([]);           // [object Array]
classof(/ /.);          // [object RegExp]
classof(new Date());   // [object Date]
classof(window);       // [object Window]
Copy the code

3. Scalability

The extensibility of an object indicates whether new properties can be added to the object. All built-in and custom objects are display extensible.

Test scalability

  • Object.isExtensible()
  • Object.isSealed()
  • Object.isFrozen()

Ways to influence extensibility

  • Object.preventExtensions()
  • Object.seal()
  • Object.freeze()

Pay attention to

  • Once you become unscalable, you can’t go back to being scalable
  • The preventExtensions only affect the extensibility of the object itself
var a = {};
Object.isExtensible(a); // true
Object.preventExtensions(a); // Object.seal() and object.freeze ()
a.name = 'a';
a;  / / {}
Object.isExtensible(a); // false
Copy the code

Object methods

These methods are largely inherited from prototypes.

The method name function note
hasOwnProperty() Detect own properties
propertyIsEnumerable() Checks its own property and its enumerability is true
isPrototypeOf() Tests whether an object exists on another object’s prototype chain
toString() Returns a string representing the value of the object calling this method
toLocaleString() Returns a string of localized objects
toJSON() Returns the serialized result
valueOf() Converts an object to its original value
var a = {name: 123};
a.toString(); // [object Object]
a.toLocaleString(); // [object Object]
a.valueOf(); // {name: 123}

var b = [1.2.3] / / 1, 2, 3
b.toString(); / / 1, 2, 3
b.toLocaleString();
b.valueOf(); / / [1, 2, 3]

var d = new Date(a); d.toString();// Fri Aug 28 2020 11:29:42 GMT+0800
d.toLocaleString(); // 2020/8/28 11:29:42 am
d.toJSON(); / / the 2020-08-28 T03: continual. 460 z
d.valueof(); / / 1598585382460
Copy the code

Object constructor

attribute

  • Object.length: The value is 1
  • Prototype: Can add attributes to all objects of type Object

methods

ES5

The method name function
Object.create() Creates a new object with the specified prototype object and properties
Object.defineProperty() Adds a property to an object and specifies the configuration for that property
Object.defineProperties() Add multiple properties to an object and specify their configuration separately
Object.getOwnPropertyNames() Returns an array containing all enumerable and non-enumerable property names for the specified object
Object.getOwnPropertySymbols() Returns an array containing all the symbolic properties of the specified object itself
Object.getOwnPropertyDescriptor() Returns the property configuration specified by the object
Object.isExtensible() Determines whether an object is extensible
Object.preventExtensions() Prevents any extension of the object
Object.seal() To create a “sealed” Object, call Object.PreventExtensions () and mark all properties as 64x :false
Object.isSealed() Check whether the object is sealed
Object.freeze() Create a “freeze” Object, actually calling Object.seal() and marking all properties as writable:false
Object.isFrozen() Check whether the object is frozen

ES6

The method name function
Object.is() Compares whether two values are the same. All NaN values are equal (this is different from == and ===)
Object.assign() Create a new object by copying one or more objects
Object.getOwnPropertyDescriptors() Returns a description object for all attributes of the object
Object.setPrototypeOf() Sets the object’s Prototype (that is, the internal [[Prototype]] property)
Object.getPrototypeOf() Returns the prototype object of the specified object
Object.keys() Returns an array containing the names of all the given object’s own enumerable properties
Object.values() Returns an array of the given object’s own enumerable values
Object.entries() Returns a [key, value] array of the given object’s own enumerable properties
Object.fromEntries() The inverse operation of Object.entries() to turn an array of key-value pairs into objects