Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of the meaning and function of JavaScript object

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "the meaning and function example analysis of JavaScript object". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "the meaning and function of JavaScript object example analysis"!

one。 Overview

An object is a compound value that aggregates many values (original values or other objects) that can be accessed through property names. The property name can be any string that contains an empty string. JavaScript objects can also be called a data structure, as we often hear of "hash", "hashtable", "dictionary", "associative array".

Objects in JavaScript can be divided into three categories:

① built-in objects, such as arrays, functions, dates, etc.

② host object, which is defined by the hosting environment (such as browser) embedded in the JavaScript interpreter, such as HTMLElement, etc.

③ custom objects, which programmers define in code

The properties of an object can be divided into two categories:

① 's own property (own property): an attribute defined directly in an object

② inheritance property (inherited property): properties defined in the prototype object of the object (more on prototype objects below)

two。 Creation of object

Since you learn objects, how can you not know how to create objects? Students interviewing for front-end positions may have been asked this basic question:

What are two ways to create a JavaScript object? (or: tell me how to create a JavaScript object? )

I've only been asked this question twice. There are many ways to create objects on the Internet, but according to the books I read, there are three ways! Let's talk about these three methods in detail:

1. Object direct quantity

A mapping table consisting of several name / value pairs, separated by colons, separated by commas, and the entire mapping table enclosed in curly braces. The attribute name can be a JavaScript identifier or a string literal, which means that the following two ways to create an object obj are exactly the same:

Var obj = {x: 1, y: 2}

Var obj = {'xdye: 1,' yawning rig 2}

two。 Create objects through new

The new operator is followed by a function call, the constructor, to create and initialize a new object. For example:

1 var o = new Object (); / / create an empty object, just like {}

2 var a = new Array (); / / create an empty array, just like []

3 var d = new Date (); / / create a Date object that represents the current time

We'll talk about constructors later.

3.Object.create ()

ECMAScript5 defines a method called Object.create (), which creates a new object, where * parameters are the prototype object of the object (it seems that the prototype object hasn't been released yet. The second optional parameter is used to further describe the properties of the object, and the second parameter will be discussed below (because this third method is defined in ECMAScript5, people often talk about the two methods of creating objects in the past, right? Personally, I think that should be the reason. This method is easy to use:

1 var o1 = Object.create ({x: 1, y: 2}); / / object o1 inherits attributes x and y

2 var O2 = Object.create (null); / / object O2 has no prototype

The following three are exactly the same:

1 var obj1 = {}

2 var obj2 = new Object ()

3 var obj3 = Object.create (Object.prototype)

To explain why these three ways are exactly the same, let's first explain the prototype objects in JavaScript (alas, thank you for waiting! ), remember that a great god once said:

Javascript is an object-based-based language, and almost everything you encounter is an object. However, it is not a true object-oriented programming (OOP) language because it does not have class (classes) in its syntax.

Object-oriented programming language JavaScript, no classes! So, how does it implement inheritance? Yes, through the prototype object. Basically every JavaScript object (except null) is associated with another object, and the "other" object is the so-called prototype object (the prototype object can also be referred to as a prototype for short, it's not as complex as you might think, it's just an object). Each object inherits properties from the prototype object, and the value of an object's prototype property (which is automatically generated by default when the object is created and does not require display customization) is the prototype object of the object, that is, obj.prototype is the prototype object of the object obj.

First of all, let's go back to the above question. With the understanding of the prototype object, here are the rules of the JavaScript language that do not require too much explanation:

① the prototype object of all objects created by the direct amount of objects is the Object.prototype object.

The prototype object of the object created by ② through the keyword new and constructor is the value of the constructor prototype property, so the prototype of the object created by constructor Object is Object.prototype.

Now it also complements the meaning of the third method of creating objects, Object.create () * * parameters.

three。 Query and setting of properties

It's not enough to learn how to create an object, because only when an object has some properties can it really work! So, move on to learn the properties of the object!

You can get and set the value of a property through the dot (.) or square bracket ([]) operator. For a dot (.), on the right must be an identifier named after the attribute name (Note: JavaScript identifiers have their own legal rules, which are different from quoted strings). For square brackets ([]), there must be a string expression inside the square brackets (string variables, of course, and other values that can be converted into strings, such as numbers, etc.), which is the name of the attribute. As an example:

Var obj = {x: 1, y: 2}; obj.x = 5; obj ['y'] = 6

As mentioned in the overview, JavaScript objects have "own properties" as well as "inherited properties." When querying the attribute x of the object obj, it will first look for whether there is x in the attribute of the object obj. If not, it will find whether the prototype object obj.prototype of the object obj has the attribute x, and if not, it will then look up whether the prototype object obj.prototype.prototype of the object obj.prototype has the attribute x, until x is found or the prototype object found is the object of undefined. As you can see, an object inherits a lot of prototype objects, and these prototype objects form a "chain", which is what we usually call "prototype chain", which is also called "prototype inheritance" (prototypal inheritance) in JavaScript.

Object o queries a property step by step along the prototype chain, but when it sets the value of a property, it only modifies its own property (if the object does not have this property, it will be added and assigned). Does not modify the properties of other objects on the prototype chain.

four。 Accessor properties getter and setter

What we have mentioned above are very common object properties, which are called "data attributes" (data property), and data properties have only a simple value. In ECMAScript 5, however, attribute values can be replaced by one or two methods, getter and setter, and attributes defined by getter and setter are called "accessor properties" (accessor property).

When the program queries the value of the accessor property, JavaScript calls the getter method (with no parameters). The return value of this method is the value of the property access expression. When the program sets the value of an accessor property, JavaScript calls the setter method, passing the value to the right of the assignment expression as a parameter to setter. If the property has both getter and setter methods, then it is a read / write property; if it has only the getter method, then it is a read-only property, and assigning a value to the read-only property will not report an error, but it will not succeed; if it has only the setter method, then it is a write-only property, and the read-only property always returns undefined. Look at a practical example:

Var p = {x: 1.0,2.0, get r () {return Math.sqrt (this.x*this.x + this.y*this.y);}; set r (newvalue) {var oldvalue = Math.sqrt (this.x*this.x + this.y*this.y); var ratio = newvalue/oldvalue; this.x* = ratio; this.y* = ratio }, get theta () {return Math.atan2 (this.y, this.x);}, print: function () {console.log (y:'+this.y);}}

As the example writes, the accessor property defines one or two functions with the same name as the property. This function definition does not use the function keyword, but uses get and set, and does not use a colon to separate the property name from the function body. By contrast, the following print property is a functional method. Note: the usage of the this keyword in getter and setter here, JavaScript calls these functions as methods of the object, that is, the this in the body of the function points to the object. Let's take a look at the running results of the instance:

Just like the output from the console, r and theta are just a value attribute, and print is a method attribute, as is the case with XMagi y.

The addition of this accessor in ECMAScript 5 is more complex than ordinary properties, but it also makes the key-value pairs of object properties more rigorous.

five。 Delete attribut

Programmer code is generally to achieve add, delete, change, check the function, the previous has said to add, change, check, let's talk about deletion!

The delete operator removes properties from an object, and its Operand should be a property access expression. However, delete just disconnects the property from the host object and does not manipulate the properties in the property:

Var a = {p: {XRV 1}}; var b = a.p; delete a.p

After the execution of this code, the value of b.x is still 1. Because references to deleted properties still exist, sometimes this loose code can cause memory leaks, so when destroying an object, you should traverse the properties in the properties and delete them in turn.

If the delete expression returns true:

When ① deletes successfully or without any side effects (such as deleting attributes that do not exist)

② if the delete is not an attribute access expression

Var obj = {x: 1 get r () {return 5;}, set r (newvalue) {this.x = newvalue;}}; delete obj.x; / / delete the attribute x of the object obj, return true delete obj.x; / / delete the attribute that does not exist, return true delete obj.r; / / delete the attribute r of the object obj, return true delete obj.toString / / without any side effects (toString is inherited and cannot be deleted), return true delete 1; / / the number 1 is not an attribute access expression, but true

If the delete expression returns false:

When ① removes configurability (configurability is a property of a property, discussed below) when it is a property of false

The delete Object.prototype; / / return false,prototype property is not configurable

/ / variables declared by var or functions declared by function are non-configurable properties of global objects

Var x = 1

Delete this.x; / / returns false

Function f () {}

Delete this.f; / / returns false

six。 Properties of attribut

The configurability of attributes has been mentioned above, because the concepts of the properties of attributes are also used in the detection and enumeration properties, so let's talk about the properties of attributes first.

In addition to containing names and values, properties contain three properties that identify them as writable, enumerable, and configurable. These features cannot be set in ECMAScript 3, and all properties created by ECMAScript 3 programs are writable, enumerable, and configurable, and cannot be modified. API for querying and setting these attribute properties is provided in ECMAScript 5. These API are very useful for library developers because:

① can use these API to add methods to prototype objects and make them non-enumerable, which makes them more like built-in methods

Through these API, ② can "lock" an object by defining properties that cannot be modified or deleted

Here we treat the getter and setter methods of accessor properties as properties of the property. According to this logic, we can also think of the value of an attribute as a property of an attribute. Therefore, it can be considered that the attribute contains a name and four properties. The four properties of a data property are its value, writable, enumerable, and configurable. Accessor properties do not have value properties and writeability, and their writability is determined by the existence of setter methods. Therefore, the four properties of accessor properties are get, set, enumerability, and configurability.

In order to query and set attribute properties, ECMAScript 5 defines an object called attribute descriptor (property descriptor), which represents those four properties. The properties of the descriptor objects have the same name as the properties they describe. Therefore, the properties of the descriptor object for data properties are value, writable, enumerable, and configurable. The descriptor object of the accessor property replaces value and writable with the get property and the set property. Where writable, enumerable, and configurable are Boolean values, and of course, the get and set properties are function values. You can get the property descriptor for a specific property of an object by calling Object.getOwnPropertyDescriptor ():

As you can see from the name of the function, Object.getOwnPropertyDescriptor () can only get the descriptor of its own property, and it returns undefined for both inherited and non-existent properties. To get the properties of inherited properties, you need to traverse the prototype chain (not the prototype chain? Don't worry, we'll talk about it later.

To set the property of a property, or to make a new property have a property, you need to call Object.definePeoperty (), passing in the object to be modified, the name of the property to be created or modified, and the property descriptor object:

You can see:

The attribute descriptor object passed into Object.defineProperty () by ① does not have to contain all four attributes

② writeability controls the modification of attribute values

③ enumerability controls whether properties can be enumerated (enumerated properties, as we'll see below)

④ configurability controls changes to other features, including whether the previously mentioned attributes can be deleted

If you want to modify or create multiple properties at the same time, you need to use Object.defineProperties (). The * parameter is the object to be modified, and the second parameter is a mapping table that contains the names of the properties to be created or modified, as well as their property descriptors, such as:

Var p = Object.defineProperties ({}, {x: {value: 1, writable: true, enumerable: true, configurable: true}, y: {value: 2, writable: true, enumerable: true, configurable: true}, r: {get: function () {return 88;}, set: function (newvalue) {this.x = newvalue;}, enumerable: true, configurable: true}, greet: {value: function () {console.log ('hello,world') }, writable: true, enumerable: true, configurable: true}})

I believe you have also seen from the example that both Object.defineProperty () and Object.defineProperties () return the modified object.

When we talked about getter and setter accessor properties earlier, we used object direct syntax to define accessor properties for new objects, but we could not query the getter and setter methods of properties or add new accessor properties to existing objects. In ECMAScript 5, you can do this with Object.getOwnPropertyDescriptor () and Object.defineProperty ()! But before ECMAScript 5, most browsers (with the exception of IE) already supported get and set writing in object literal syntax. So these browsers also provide non-standard old-fashioned API for querying and setting getter and setter. These API consist of four methods, all of which are owned by objects. _ _ lookupGetter__ () and _ _ lookupSetter__ () are used to return the getter and setter methods of a named attribute. _ _ defineGetter__ () and _ _ defineSetter__ () are used to define getter and setter. These four methods are prefixed by two underscores and suffixed by two underscores to show that they are non-standard square methods. Here is how they are used:

seven。 Detection attribute

JavaScript objects can be seen as a collection of attributes, so we sometimes need to determine whether a property exists in an object, which is what we will talk about next.

There are also three ways to detect the properties of an object, so let's talk about their functions and differences in detail below!

1.in operator

On the left side of the in operator is the property name (string), and on the right is the object. Returns true if the object's own property or inherited property contains this property, otherwise it returns false.

In order to experiment, we first add an enumerable attribute m and a non-enumerable attribute n to the object Object.prototype; then, we define two enumerable attributes x and one non-enumerable attribute y to the object obj, and the object obj is created in the form of object direct quantities, inheriting Object.prototype. Let's look at an example:

From the running results, you can see that the in operator is the property name (string) on the left and the object on the right. True is returned if this property is included in the object's own or inherited properties (whether they are enumerable or not), otherwise false is returned.

2.hasOwnProperty ()

The object's hasOwnProperty () method is used to detect whether a given name is an object's own property (regardless of whether these properties are enumerable or not), and it returns false for inherited properties. Let's look at an example:

3.propertyIsEnumerable ()

PropertyIsEnumerable () is an enhanced version of hasOwnProperty (), which returns true only if it detects that it is an own property and that the property enumerability is true. Or an example:

eight。 Enumerate properties

Enumeration properties are more commonly used than detection properties. Enumerated properties We usually use for/in loops, which can iterate through all enumerable own and inherited properties of the object in the body of the loop, assigning the property name to the loop variable. Continue with the previous example:

I used to think that for/in loops have a lot to do with in operators, but now it seems that their rules are not the same! Of course, if you don't want to traverse the inherited properties here, add a layer of hasOwnProperty () judgment to the for/in loop:

For (prop in obj) {if (obj.hasOwnProperty (prop)) {console.log (prop);}}

In addition to the for/in loop, ECMAScript 5 defines two functions that can enumerate property names:

① Object.getOwnpropertyNames (), which returns the names of all owned properties of the object, whether enumerable or not

② Object.keys (), which returns the names of enumerable own properties in the object object

Or an example:

nine。 Three special properties of an object

Each object has associated prototypes (prototype), classes (class), and extensibility (extensible attribute). These three are the special properties of the object (they are just the properties of the object, not as complex as you might think).

1. Prototype attribute

As mentioned earlier, the prototype properties of the object are used to inherit the properties. This attribute is so important that we often refer to "o's prototype attribute" directly as "o's prototype". The prototype property is set at the beginning of the instance creation (that is, the value of this property is automatically set by JavaScript by default. We will talk about how to set it manually later), as mentioned earlier:

Objects created by ① from object direct quantities use Object.prototype as their prototype

Objects created by ② through the new+ constructor use the prototype property of the constructor as their prototype

Objects created by ③ through Object.create () use * parameters (if this parameter is null, the object prototype property value is undefined;. If this parameter is undefined, an error will be reported: Uncaught TypeError: Object prototype may only be an Object or null: undefined) as their prototype

So how do you query the prototype properties of an object? In ECMAScript 5, passing an object as a parameter to Object.getPrototypeOf () can query its prototype, for example:

However, in ECMAScript 3, there is no Object.getPrototypeOf () function, but the expression obj.constructor.prototype is often used to detect the prototype of an object, because each object has a constructor property that represents the object's constructor:

The constructor property of an object created by ① through an object direct quantity points to the constructor Object ().

The constructor property of the object created by ② through the new+ constructor points to the constructor

The constructor property of the object created by ③ through Object.create () points to the same point as the constructor property of its prototype object.

To detect whether an object is a prototype of another object (or is in a prototype chain), you can use the isPrototypeOf () method. For example:

There is also a non-standard, but many browsers have implemented the object property _ _ proto__ (also two underscores start and end to indicate that it is non-standard), used to directly query / set the prototype of the object.

two。 Class attribute

The class property (class attribute) of an object is a string that represents the type information of the object. Neither ECMAScript 3 nor ECMAScript 5 provides a way to set this property, and there is only one indirect way to query it. The default toString () method (inherited from Object.prototype) returns a string of this format: [object class]. Therefore, to get the class of an object, you can call the object's toString () method, and then extract the characters between the eighth and the penultimate position of the returned string. However, the toString () method inherited by many objects is overridden (for example, Array, Date, and so on), and in order to call the correct version of toString (), the Function.call () method must be called indirectly. The following code returns the class of any object passed to it:

Function classof (obj) {

If (o = null) {

Return 'Null'

}

If (o = undefined) {

Return 'Undefined'

}

Return Object.prototype.toString.call (o) .slice (8,-1)

}

The classof () function can pass in any type of argument. The following are examples of usage:

Summary: from the running results, you can see that the class attribute of the object created in the three ways is' Object'.

3. Expandability

The extensibility of an object is used to indicate whether new properties can be added to the object. All built-in and custom objects are shown to be extensible (unless they are converted to non-extensible), and the extensibility of host objects is defined by the JavaScript engine. Functions for querying and setting object extensibility are defined in ECMAScript 5:

① (query) determines whether an object is extensible by passing it into Object.isExtensible ().

② (setting) if you want to convert an object to non-extensible, you need to call Object.preventExtensions (), passing in the object to be converted as a parameter. Note:

a. Once an object is converted to non-extensible, it can no longer be converted back to extensible

B.preventExtensions () only affects the extensibility of the object itself. If you add properties to the prototype of a non-extensible object, the non-extensible object will also inherit these new properties.

Further, Object.seal () is similar to Object.preventExtensions () in that, in addition to making the object non-extensible, all of the object's own properties can be set to non-configurable. Objects that have been closed (sealed) cannot be unsealed. You can use Object.isSealed () to detect whether the object is closed.

Further, Object.freeze () will lock the object more strictly-- "frozen". In addition to making the object non-extensible and its properties non-configurable, you can also set all of its own data properties to read-only (if the object's accessor properties have setter methods, the accessor properties will not be affected and can still be called by assigning a value to the properties). Use Object.isFrozen () to detect whether the object is summarized.

Summary: Object.preventExtensions (), Object.seal (), and Object.freeze () all return incoming objects, that is, they can be called in a nested manner:

Var obj = Object.seal (Object.freeze ({value 1}), {y: {value: 2, writable: true}))

This statement uses the Object.create () function to pass in two parameters, that is, the * parameter is the prototype object of the created object, and the second parameter is the property that is defined directly to the object when the object is created, along with the property of the property.

ten。 Serialization of objects

After talking about the properties of the object and the properties of the object, there are still a lot of things. I don't know if you are dizzy. However, here is the lighter topic!

Object serialization (serialization) refers to converting the state of an object to a string, or you can restore a string to an object. ECMAScript 5 provides built-in functions JSON.stringify () and JSON.parse () to serialize and restore objects. These methods all use JSON as the data interchange format. The full name of JSON is "JavaScript Object Notation"-- JavaScript object representation, and its syntax and JavaScript object syntax are very similar to those of array direct quantities:

The jsonObj of * is a deep copy of obj.

The syntax of JSON is a subset of JavaScript, and it does not represent all the values in JavaScript. Support for objects, arrays, strings, infinite numbers, true, false, and null, and they can be serialized and restored. Note:

The result of ① NaN, Infinity, and-Infinity serialization is null

② JSON.stringify () can only serialize the enumerable own properties of an object

The result of serialization of ③ date objects is date strings in ISO format (see the Date.toJSON () function), but JSON.parse () still retains their string form and cannot restore them to the original date object.

④ functions, RegExp, Error objects, and undefined values cannot be serialized and restored

Of course, both JSON.stringify () and JSON.parse () can accept a second optional parameter to customize a custom serialization or restore operation by passing in a list of properties that need to be serialized or restored, which we'll talk about later.

At this point, I believe you have a deeper understanding of the "analysis of the meaning and function of JavaScript objects". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report