This is the 18th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Object description
Prototypal inheritance is a core feature of JavaScript. The most common uses of an object are to create (create), set (set), find (query), delete (delete), detect (test), and enumerate (enumerate) its properties.
The attribute name can contain any string, including an empty string.
Property Attributes
- Writable Attribute: indicates whether the value of the attribute can be set.
- Enumerable Attribute, which indicates whether the attribute can be returned through a for/in loop.
- You can configure a different attribute, which indicates whether the attribute can be deleted or modified.
Object Attributes
- Object’s prototype refers to another object whose properties inherit from its prototype.
- An object’s class is a string that identifies the type of the object.
- The object’s extensible Flag indicates (in ES5) whether new properties can be added to the object.
Related terms
-
Native objects are objects or classes defined by the ECMAScript specification. For example, arrays, functions, dates, and regular expressions are all built-in objects.
-
Host objects are defined by the hosting environment (such as a Web browser) in which the JavaScript interpreter is embedded. HTMLElement objects representing the structure of a web page in client-side JavaScript are all host objects. Since methods defined by the host environment can be treated as normal JavaScript function objects, host objects can also be treated as built-in objects.
-
User-defined objects are objects created by running JavaScript code.
-
Own properties are properties defined directly in an object.
-
Inherited Properties are properties defined in an object’s prototype object.
Create an object
Create objects by using the Object direct, keyword new, and (in ES5) object.create () functions
Object direct an object direct is an expression that creates and initializes a new object with each operation. If the value is evaluated, the property value may be different in multiple calls. The comma after the last attribute is ignored.
The keyword new new is followed by a constructor that initializes a newly created object.
Prototype chain
- All objects created directly from objects have the same prototype Object, and a reference to the prototype Object can be obtained through Object.prototype.
- The prototype of the object created through the keyword new and constructor calls is the value of the constructor’s Prototype property. Also inherited from Object.prototype. Prototype objects created by new Array() are array.prototype objects created by new Date() are date.prototype objects.
- Prototype An Object without a prototype. It does not inherit any attributes.
All other stereotype objects are ordinary objects, and ordinary objects have stereotypes.
- All built-in constructors (and most custom constructors) have a prototype inherited from Object.prototype. For example, the properties of date.prototype inherit from Object.prototype, so the properties of a Date Object created by new Date() inherit from both Date.prototype and Object.prototype.
- Null no prototype
Object.create() Object.create() is a static function, not a method provided to be called by an Object.
var o1 = Object.create({x:1.y:2}); // o1 inherits attributes x and y
// Create a new object without a prototype
var o2 = Object.create(null); // O2 does not inherit any attributes or methods
// Create a plain empty object
var o3 = Object.create(Object.prototype); //o3 and {} are the same as new Object()
Copy the code
Inherit () prevents library functions from inadvertently modifying uncontrolled objects. Modifying the attribute value of an inherited object only affects the inherited object itself.
// inherit() returns a new object that inherits properties from the stereotype object P
// Use the object.create () function in ECMAScript 5 (if it exists)
// If object.create () does not exist, degenerates using another method
function inherit(p) {
if (p == null) throw TypeError(a);// p is an object, but cannot be null
if (Object.create) // If object.create () exists
return Object.create(p); // Use it directly
var t = typeof p; // Otherwise, further test
if(t ! = ="object"&& t ! = ="function") throw TypeError(a);function f() {}; // Define an empty constructor
f.prototype = p; // Set its stereotype property to p
return new f(); // create an inherited object of p with f()
}
Copy the code
Properties to query and set
Array elements are indexed by strings rather than numbers. Such arrays are what we call associative arrays, also known as hashes, maps, or dictionaries. JavaScript objects are associative arrays.
The “own property” is aware of inheritance only when the property is queried, and setting the property has nothing to do with inheritance (override)
- The attribute assignment operation first checks the stereotype chain to determine whether the assignment operation is allowed.
- If attribute assignment is allowed, it will always create attributes on the original object or assign values to existing attributes without modifying the stereotype chain.
Null and undefined have no attributes. Querying the attributes of these values will result in an error, and setting the attributes will also result in a type error.
var len = book &&book.subtitle &&book.subtitle.length;
Copy the code
Object properties fail to be set
- Property P in o is read-only: read-only properties cannot be reassigned (the defineProperty() method makes an exception for reassigning configurable read-only properties).
- The property p in o is an inherited property, and it is read-only: you cannot override a read-only inherited property with a property of the same name.
- O does not have its own property P: O does not use setter methods to inherit property P, and the extensible attribute of O is false. If p does not exist in o and there is no setter method to call, p must be added to O. But if O is not extensible, new attributes cannot be defined in O.
delete
The DELETE operator can delete only its own properties, not inherited properties.
a={p: {x:1}}; b=a.p;delete a.p;
b.x // => 1 The deleted reference still exists
Copy the code
It returns true when the DELETE expression is deleted successfully or without any side effects (such as deleting a nonexistent property). If delete is not an attribute access expression, delete also returns true:
o = {x:1}; // o has an attribute x and inherits the attribute toString
delete o.x; // Delete x, return true
delete o.x; // Do nothing (x no longer exists), return true
delete o.toString; // Do nothing (toString is inherited), return true
delete 1; // meaningless, returns true
` `'js delete cannot delete properties whose configurability is false, such as global object properties created through variable declarations or function declarations. When deleting a configurable property of a global object in non-strict mode, you can omit the reference to the global object and simply follow the delete operator with the name of the property to be deleted` `js
this.x = 1; // Create a configurable global property (without var)
delete x; // Delete it
Copy the code
Test attributes
Determines whether a property exists in an object
-
The in operator returns true if the object’s own or inherited property contains this property:
-
HasOwnPreperty () is an object’s own property. For inherited attributes it will return false:
-
PropertyIsEnumerable () returns true only if it detects that it has its own property and the enumerable attribute is true. Properties typically created by JavaScript code are enumerable
-
Through the property query using “! == “Checks whether an attribute is undefined
==in can distinguish between properties that do not exist and properties that do exist but have a value of undefined. = =
var o = { x: undefined } // Attribute is explicitly assigned to undefinedo.x ! = =undefined // false: The property exists but the value is undefinedo.y ! = =undefined // false: The attribute does not exist
"x" in o // true: The attribute exists
"y" in o // false: The attribute does not exist
delete o.x; // Delete attribute x
"x" in o // false: The attribute no longer exists
// If o contains attribute x and x is not null or undefined, o.x is multiplied by 2.
if(o.x ! =null) o.x *= 2;
If o contains attribute x and the value of x cannot be converted to false, multiply o.x by 2.
// If x is undefined, null, false, "", 0, or NaN, it remains unchanged
if (o.x) o.x *= 2;
Copy the code
Enumerated attribute
A for/in loop can iterate through all enumerable properties (both owned and inherited) of an object in the body of the loop. The built-in methods that an object inherits are not enumerable, but the properties that you add to an object in your code are enumerable.
for (p in o) {
if(! o.hasOwnProperty(p))continue; // Skip inherited attributes
}
for (p in o) {
if (typeof o[p] === "function") continue; // Skip the method
}
Copy the code
Object.keys(), which returns an array of the enumerable names of the Object’s own properties. Object. GetOwnPropertyNames (), returns the Object name all its properties, including an enumeration.
getter setter
Properties defined by getters and setters are called accessor properties. They are different from data properties, which have a single value. Accessor properties do not have writable attributes. If it only has setter methods, then it’s a write-only property, and reading a write-only property always returns undefined. Accessor properties are inheritable.
For example, the expression "random.ocTET" generates a random number
// Generate a random number between 0 and 255 each time
var random = {
get octet() {
return Math.floor(Math.random() * 256);
},
get uint16() {
return Math.floor(Math.random() * 65536);
},
get int16() {
return Math.floor(Math.random() * 65536) - 32768; }};Copy the code
Properties of attributes
- Adding methods to prototype objects and making them non-enumerable makes them look more like built-in methods.
- “Lock” an object by defining properties that cannot be modified or deleted.
The four features of a data attribute are its value, writable, Enumerable, and configurable. The four properties of accessor properties are read (GET), write (set), enumerability, and configurability.
Objects in property descriptors
- The descriptors of data properties object are Value, Writable, Enumerable, and 64x.
- The descriptor object properties of the accessor property are GET, set, Enumerable, and 64x.
- Writable, Enumerable, and cis are all Boolean values, and the get and set properties are different functions
Object. GetOwnPropertyDescriptor descriptor () to obtain their own attributes. Return undefined for inherited and nonexistent properties. To obtain the properties of inherited properties, you need to traverse the prototype chain object.getProtoTypeof ().
Object.defineproperty () Object.defineProperties()
// For newly created properties, the default property value is false or undefined
var o = {};
Object.defineProperty(o,'x', {value:1});
//{value: 1, writable: false, enumerable: false, configurable: false}
Object.getOwnPropertyDescriptor(o, 'x');
Copy the code
- If an object is not extensible, you can edit existing properties, but you cannot add new properties to it.
- If a property is not configurable, its configurability and enumerability cannot be modified.
- If an accessor property is not configurable, its getter and setter methods cannot be modified or converted to a data property.
- If a data property is not configurable, it cannot be converted to an accessor property.
- If a data property is not configurable, its writability cannot be changed from False to true, but it can be changed from true to false.
- If a data attribute is not configurable and writable, its value cannot be modified. However, the value of a configurable but non-writable attribute can be modified (in effect, it is marked as writable, then its value is modified, and finally converted to non-writable).
== is prefixed with two underscores and suffixed with two underscores to indicate that they are non-standard methods ==
Object properties
Prototype attribute The prototype attribute of an object is used to inherit attributes. Usually the “archetypal properties of O” are called “archetypal of O”. IsPrototypeOf () checks if an Object is a prototype of another Object (or is in a prototype chain).
Class attribute Indicates the type of an object.
function classof(o) {
if (o === null) return "Null";
if (o === undefined) return "Undefined";
return Object.prototype.toString.call(o).slice(8, -1);
}
classof(null)//=>"Null"
classof(1)//=>"Number"
classof("")//=>"String"
classof(false)//=>"Boolean"
classof({})//=>"Object"
classof([])//=>"Array"
classof(/ /.) //=>"RegExp"
classof(new Date()) //=>"Date"
classof(window) //=>"Window"
function f(){}
classof(new f()) //=>"Object"
Copy the code
Extensible Attribute Indicates whether new attributes can be added to an object. All built-in, custom objects are explicitly extensible. The goal is to “lock” the object to avoid outside interference.
- Object.jsextensible () to determine whether the Object is extensible.
- Object.preventextensions () converts the Object to non-extensible. Once an object is made unextensible, it cannot be made extensible. Only the extensibility of the object itself is affected; the object inherits new properties when its prototype adds attributes.
- Object.seal() can make an Object unextensible, making all of its own properties unconfigurable.
- No new properties can be added to this object, and its existing properties cannot be deleted or configured, although its existing writable properties can still be set. Objects that have already been sealed cannot be unsealed. Object.issealed () to check whether the Object isSealed.
- Object. Freeze () Frozen. In addition to making an object non-extensible and its properties non-configurable, you can also make all of its own data properties read-only (if the object’s accessor properties have setter methods, the accessor properties are unaffected and can still be called by assigning values to the properties). Object.isfrozen () to check whether the Object isFrozen.
Serialization
To convert the state of an object to a string or to restore a string to an object.
- NaN, Infinity, and -infinity serialize to null
- Date objects are serialized as ISO Date strings (date.tojson ()), but json.parse () retains their string form and does not restore them to the original Date objects.
- Functions, RegExp, Error objects, and undefined values cannot be serialized and restored.
- Json.stringify () can only serialize the object’s enumerable own properties.