object

Without 100% mastery of objects, programming can be difficult. This article will be a long one, readers need to be patient!!

In the “this” article, we’ve been referring to an object, but what exactly is an object?

grammar

Text grammar

const obj = {
    a: 1.b: 2,}Copy the code

Construction grammar

const obj = new Object(a);Copy the code

Constructional forms and literal forms generate the same objects. The only difference is that in a literal declaration you can add multiple key/value pairs, but in a construct you must add attributes one by one.

type

There are six main types in JavaScript (the term is “language types”)

  • string
  • number
  • boolean
  • null
  • undefined
  • object

Simple basic types: string, Boolean, number, NULL, and undefined. Null is sometimes referred to as an object type, but this is really just a bug in the language that typeof NULL returns the string “object”. But NULL itself is a primitive type.

Complex primitive types: also known as reference types, obkect. There are many special object subtypes at the same time. Subtypes extend the functionality of objects. For example, functions and arrays are subtypes of objects. Here are the object subtypes.

Built-in objects

Object subtypes, often referred to as built-in objects. Names look the same as simple base types, but their relationship is more complex, which we’ll cover in more detail later.

  • String
  • Number
  • Boolean
  • Object
  • Function
  • Array
  • Date
  • RegExp
  • Error

Built-in objects can be used as constructors in JS to construct a new object corresponding to a subtype. For example:

var str = 'wo shi string';
var str = new String('wo shi string');
Copy the code

Literals and constructs are declared the same way. We usually use:

console.log(str.length)
console.log(str.split(...) )Copy the code
  • Strings are not objects. Why do they have attributes? All for the built-in String object. The same goes for Number and Boolean.
  • Null and undefined have no corresponding constructs, they are only literal. In contrast, Date has only construction and no literal form.
  • Object, Array, Function, and RegExp (regular expressions) are all objects, not literals, whether they are literal or constructed.
  • Error objects are rarely created explicitly in code, but are typically created automatically when an exception is thrown. You can also use new Error(..) This construct is used to create, but is generally not needed.

content

Inside the engine, content is stored in a variety of ways, and generally not in object containers. Stored inside the object container are the names of these properties, which act like Pointers (technically references) to where the values are actually stored.

const obj = { a: 1 };
console.log(obj.a)
Copy the code

Pointers can also be represented by variables

const obj = { a: 1 };
const key = 'a';
console.log(obj[key])
Copy the code

Property names are always strings. If you use a value other than the property name, it is first converted to a string.

  • Object to [object object];
  • The number 111 becomes ‘111’;
  • True converts to ‘true’;
  • .

You can try more

const obj = {};
const obj2 = {};
obj[obj2] = 111;
console.log(obj['[object Object]']) / / 111
Copy the code

The name of the computable property

ES6 added computable attribute names that can be wrapped around an expression in literal form with [] :

const key = 'foo';
const obj = {
    [key + 'bar'] :'foobar'
};
console.log(obj['foobar']) // foobar
Copy the code

Function as attribute

If the attribute value of an object is a function, the function is often called a ‘method’. This will affect the direction of this in the function. For details, see this for a comprehensive analysis.

An array of

Arrays are object subtypes that have a more structured mechanism for storing values (though they still don’t limit the type of values).

Array properties

Arrays expect numeric subscripts, that is, the locations where values are stored (often called indexes) are non-negative integers:

const arr = [1.2.3.'foo'];
console.log(arr[1]) / / 2
console.log(arr[3]) // foo
Copy the code

Arrays are also objects, so you can still add attributes to arrays even though each subscript is an integer: non-numeric subscripts, however, will only have storage, will not affect the value of the Length attribute, and will affect performance, so try not to use them.

const arr = [1.2.3.'foo'];
console.log(arr.length) / / 4
arr.baz = 'baz';
console.log(arr.length) / / 4
console.log(arr.baz) // baz
Copy the code

If you try to add an attribute to an array, but the attribute name “looks” like a number, it becomes a numeric subscript.

const arr = [1.2.3];
console.log(arr.length) / / 3
arr['3'] = 'baz';
console.log(arr.length) / / 4
console.log(arr['3']) // baz
Copy the code

Object storage

Objects are stored differently from primitive types. Identifiers (names) and values of common types are stored 1-to-1. Objects are extensible and flexible in size, so they are stored differently. There can be multiple identifiers that correspond to the same value. Here is a detailed analysis:

var str = 'wo shi string';
var obj1 = {a: 1};
var num = 1;
var obj2 = obj1;
var obj3 = {a: 1};
Copy the code

The above code is stored like this:

Obj1 and obj2 refer to the same data. Obj3 is not the same data although it has the same value as obj1 and obj2. Here’s a confirmation:

console.log(obj1 === obj2) // true
console.log(obj2 === obj3) // false
console.log(obj1 === obj3) // false
Copy the code

Attribute descriptor

Each property of the object has its own descriptor: Writable, Enumerable, and freely configurable.

const obj = { a: 1 }
Object.getOwnPropertyDescriptor(obj, 'a')
/ / {
// value: 2,
// writable: true,
// enumerable: true,
// configurable: true,
// }
Copy the code

Writable

Writable determines whether the value of a property can be modified. Writable: false The attribute modification does not take effect. In strict mode, errors are reported.

const obj = { a: 1 }
Object.defineProperty('a', {writable:false
})
obj.a = 2;
console.log(obj.a) / / 1

// Strict mode
'use strict'
const obj = { a: 1 }
Object.defineProperty('a', {writable:false
})
obj.a = 2; / / an error
Copy the code

Enumerable Enumerable

This descriptor controls whether a property appears in an object’s property enumeration, such as for.. In circulation.

const obj = { a: 1 }
Object.defineProperty('a', {enumerable:false
})

for (let key in obj) {
    console.log(key) // Can't print a
}
Copy the code

Freely configurable, works without any additional control system.

DefineProperty (..) can be used as long as the attribute is configurable Method to modify the property descriptor:

const obj = { a: 1 }
Object.defineProperty('a', {configurable:false
})
Object.defineProperty('a', {enumerable:false / / an error
})
delete obj.a; / / not to take effect
Copy the code

Whether in strict mode or not, trying to modify a non-configurable property descriptor will result in an error. The delete statement (silent) failed.

invariance

If you want to control an object, it cannot be extended, modified, or deleted.

Object is constant

The writable: False and different: False allow you to create a constant property that cannot be modified, redefined or deleted.

Prohibit extensions

To disable an Object from adding new properties and keeping existing properties, use object.preventExtensions (..). :

seal

Object.seal(..) A “sealed” object is created, after which not only can no new attributes be added, but no existing attributes can be reconfigured or deleted (although the values of the attributes can be changed).

Equivalent to calling Object.preventExtensions(..) on existing objects. All existing attributes are tagged with a different :false.

freeze

Object.freeze(..) Creates a frozen Object. This method actually calls Object.seal(..) on an existing Object. And mark all “data access” properties as writable:false so that their values cannot be changed. They cannot be extended, modified, or deleted

The depth of the operation

The preventExtensions, SEAL, and Freeze are all for the current object only. If the object is multi-level, recursive operations are required.

The next article

Js you Didn’t Know – Object (2)