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

The method of creating objects by JavaScript and the examples of various modes

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

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the method of creating objects by JavaScript and the examples of various patterns". In daily operation, I believe that many people have doubts about the methods of creating objects by JavaScript and the examples of various modes. The editor has consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "the method of creating objects by JavaScript and the introduction of examples of various patterns". Next, please follow the editor to study!

1. Understanding object and object-oriented programming 1.1 object-oriented programming

Object-oriented programming (Object Oriented Programming, abbreviated as OOP) is a programming mode of thinking. It regards everything in the world as a collection of objects, and the operation of the world depends on the result of division of labor and cooperation among objects, reflecting the idea that everything is an object.

In programming, object-oriented programming can be regarded as writing various objects (modules) with specific functions and dividing them organically, that is, the current modular programming is the practical application of object-oriented programming.

1.2 understand the object

Object has been mentioned in the previous series of articles that, in terms of data characteristics, an object is a collection of unordered attributes (key-value pairs).

We can use literals and constructors to create the simplest object:

Var person = new Object (); person.name = "teren"; person.age = 18var teren = function () {console.log ("hello" + this.name);} var teren = {name: "teren", age:18, greet:function () {console.log ("hello" + this.name);}}

Usually create a simple object in a literal way

The object above is an abstract expression of the real object.

1.3 attribute types of objects

In the previous section, we can use the delete command to delete some object properties, but some can not, using the Object.keys () method can only traverse enumerable properties, so are there any properties of object properties that we don't know yet?

ES5 provides an internal-only attribute to describe various properties of the property of an object, using [[attribute]] to indicate that they cannot be accessed directly in JavaScript

A chestnut that we are very familiar with is the instance object constructed by the Number constructor.

We cannot access num directly. [[PrimitiveValue]], this property can only be accessed through num.valueOf ()

There are two properties that define object properties in ES5, data properties and accessor properties, which can be combined with object properties.

A data property defines the properties of an object's property value, and an attribute value can include the following four data properties:

[[Value]]: store attribute values; [[Writable]]: whether an attribute is writable; [[Enumerable]]: whether it is an enumerable attribute; [[Configurable]]: whether it can be deleted with the delete command

The accessor property defines the two functions getter and setter that the properties of an object call when accessing and setting properties

[[Get]]: the function called when the property is accessed

[[Set]]: function called when setting a property

These two features are explained directly with an instance object:

/ / data feature; var teren = {}; Object.defineProperty (teren, {value: "teren", writable:false, enumerable:true, configurable:true}) / / Visitor feature / / html//jsvar obj = Object.defineProperty ({}, "name", {set:function (name) {document.getElementById ('name') [xss_clean] = name}, get:function () {console.log (' name') [xss_clean])},}) obj.name = "hello world" obj.name

[demo]

Object.defineProperties can configure multiple properties of an object at once

two。 How objects are created

In the previous section, we had a preliminary understanding of object-oriented programming ideas and objects. in this section, we discuss in depth the way objects are created and their advantages and disadvantages.

Different ways of creating objects can also be simply called design patterns, and different design patterns play different roles in practical programming applications.

2.1 singleton mode

The singleton pattern is the only instance object that produces a class, and it ensures that only one object instance can actually come in handy.

In singleton mode, the object is created as follows:

Var singleton = {attr:1, method:function () {return this.attr}} var ex1 = singleton;var ex2 = singleton;ex1 = = ex2//true

The above way to create a singleton:

Advantages: very easy to use

Disadvantages: lack of encapsulation, member exposure, resource consumption during initialization

You can use closures to solve this problem:

Var substance = (function () {var unique; function init () {var type; return {setType:function (t) {return type = t;} return {getInstance:function () {if (! unique) {unique = init ();} return unique;}}) (); var Adam = substance.getInstance (); var Eve = substance.getInstance (); Adam = = EveAdam.setType ('Man') / / Man

2.2 Factory Mod

Singleton mode can only create a single instance object, that is, if the instance object is assigned to multiple variables, there will be a problem of object reference, that is, modifying one of the variables will affect the other.

Sometimes we need to create multiple objects with similar structures, only some of the properties are different, and the factory pattern comes in handy.

The design idea of the factory pattern is to be able to mass produce objects with similar properties and methods like the factory. Using the factory pattern can solve many similar problems, such as creating multiple pop-up windows (only with different titles).

Function person (name,age) {var obj = new Object (); obj.name = name; obj.age = age; obj.greet = function () {return "hello" + this.name;}; return obj} var Adam = person ("Adam", 18); var Eve = person ("Eve", 20)

The above factory model:

Advantages: the ability to batch produce objects with similar structures; encapsulate the details of creating objects

Cons: failed to address the type of object, that is, which constructor was created

2.3 Constructor model

Constructors can create specific types of objects, and native objects such as Array and RegExp can create specific types of instance objects.

Function Person (name,age) {this.name = name; this.age = age; this.greet = function () {return "hello" + this.name;}} var p1 = new Person ('Adam',18); var p2 = new Person (' Eve',20)

Using the constructor pattern, you can solve the problem of who created the instance object.

The difference between the above code and the factory pattern is:

1. Creation of new objects is not displayed

two。 Assign properties and methods directly to the this object

3. No return statement

4. The function name begins with an uppercase to distinguish the ordinary function.

5. Use the new operator to create an object instance

The principle of new operator

Using the new operator to call a function is different from calling a function directly, in which the new operator runs the function as follows:

Create a new object

Assign the scope of the constructor to the new object and execute the constructor

Code within

Return to new object

The code is represented as follows:

Function Person (name,age) {this.name = name; this.age = age; this.greet = function () {return "hello" + this.name;}} function createPerson (name,age) {var o = new Object (); Person.call (odyname); return o;} var p1 = createPerson ('Adam',18); var p2 = createPerson (' Eve',20)

The advantages and disadvantages of using constructor mode to create objects are:

Advantage: the ability to identify the constructor to which the object belongs

Disadvantages: if there are properties and methods shared by different instance objects, using constructor mode will waste memory

[note]

For more information about the this keyword, please see [what's this]

If the constructor does not use the new operator, the call is the same as the ordinary function

2.4 prototype model

Each function has a prototype prototype property that can deploy properties and methods shared by specific types of instances

Function Person () {}} Person.prototype.greet = function () {return "hello" + this.name

Deploy the original greet function on the prototype prototype property of the Person function, so that p1 and p2 can share the method, unlike the constructor model, which wastes memory by adding a greet method every time an instance is created

[note]

For more understanding of prototype objects, see the next section, JavaScript's inheritance mechanism.

The advantages and disadvantages of using prototype patterns to create objects are:

Advantages: the shared properties and methods for each instance can be better implemented.

Disadvantages: using prototype mode alone will not be able to distinguish the private properties of different instances

2.5 mixed mode

The mixed mode is the combination of the advantages and disadvantages of the constructor pattern and the prototype pattern, the private properties of the deployment instance of the constructor pattern, and the public properties of the deployment instance of the prototype pattern.

Function Person (name,age) {this.name = name; this.age = age;} Person.prototype.greet = function () {return "hello" + this.name;} var p1 = new Person ("Adam", 18); var p2 = new Person ("Eve", 20)

Mixed pattern is currently the most widely used and most recognized design pattern for creating custom types (classes).

[note]

Of course, design patterns are not only mentioned above, but also more in-depth, you can refer to the book "Design patterns" and an article "outline of Design patterns" written by Lamb before.

Inheritance Mechanism of 3.JavaScript

In the previous section, we implicitly introduced the concept of prototype object by creating different patterns of object. in this section, we will take a detailed look at the prototype object, prototype chain and the inheritance mechanism of its implementation.

Previously, from the data characteristics, we know that an object is a collection of unordered attributes (key-value pairs).

Now, from an object-oriented point of view, any object is an instance of a more abstract object, which can be understood as the concept of a class.

From this perspective, we can now redefine the meaning of objects and classes:

The object can be said to be the abstraction of real things, the object encapsulates properties and methods, the attribute value refers to the state of the object, and the method refers to the behavior of the object.

A class is an 'object' that provides a template, and it is an abstraction of the object

Take a simple chestnut:

Function Person (name,age) {this.name = name; this.age = age;} Person.prototype.greet = function () {return "hello" + this.name;} var p1 = new Person ("Adam", 18); var p2 = new Person ("Eve", 20)

The above code shows that the two instances of p1 and p2 are abstractions of the real Adam and Eve, while the "class" Person is the abstraction of the two instances, which provides a standard template for those who create similar structures.

[note] there are no classes in JavaScript before ES6, but classes are defined in ES6

3.1 prototype object

In the prototype pattern in the previous section, we mentioned that each function has a prototype property that points to the prototype object of the function and can deploy properties and methods shared by specific types of instances

More in-depth understanding of prototype prototype objects, prototype prototype objects can not only deploy properties and methods shared by specific types of instances, but also the key to the implementation of JavaScript inheritance

Whenever a new function is created, a prototype property is created for the function, and each prototype property automatically gets a constructor attribute, which points to the function pointer where the prototype property is located.

When you create an instance using the constructor, the instance contains an internal property _ _ proto__ that points to the prototype object of the constructor

As a result, a simple inheritance is created.

Take the following code as an example:

Function Person (name,age) {this.name = name; this.age = age;} Person.prototype.greet = function () {return "hello" + this.name;} var p1 = new Person ("Adam", 18); var p2 = new Person ("Eve", 20)

After the constructor is created, a prototype property is automatically created. Under the prototype prototype object, there is a default constructor attribute pointing to the function Person where the prototype attribute is located.

The greet method is deployed on the prototype prototype object. The internal property _ _ proto__ of instance p1 points to the constructor Person.prototype, thus inheriting the greet method on the prototype object of the constructor.

[note]

The _ _ proto__ of the instance points to the prototype prototype object implementation inheritance of the constructor, and this relationship exists between the instance and the constructor prototype object rather than between the constructor.

When the js engine parses the properties of an object, it will first search for the properties of the object itself, and if not, it will search for the properties on the prototype object pointed to by _ _ proto__ until it is found. If the properties defined on the object itself have the same property name as those on the prototype object, its own properties will block the properties on the prototype object when reading the property

Function Person (name,age) {this.name = name; this.age = age;} Person.prototype.greet = function () {return "hello" + this.name;} var p1 = new Person ("Adam", 18); p1.greet () / / hello Adam;p1.greet = function () {return "hello world"}

You can directly use point operations to modify the prototype object of the constructor, and the effect is to add properties directly to the original prototype object. Sometimes too many attributes need to be added, and the point operation is too troublesome. You can use the method of resetting the prototype object:

Function Person (name,age) {this.name = name; this.age = age;} Person.prototype = {constructor:Person, greet1:function () {}, greet2:function () {}, greet3:function () {}}; var p1 = new Person ("Adam", 18); Person.prototype.constructor.name// "Object"

It should be noted that after resetting the prototype object, the Person constructor is returned to the constructor property of the prototype object.

If you do not reset constructor, then the Person.prototype is an object created by literals, and the default constructor for literal objects is Object

3.2 prototype chain

Above, we define only one constructor to implement inheritance once; if there are multiple constructors and there is an inheritance relationship between them, then a prototype chain about inheritance will be formed.

Function SuperType (name,age) {this.name = name; this.age = age} SuperType.prototype.greet = function () {return "hello" + this.name} function SubType (name,age,height) {SuperType.call (this,name,age); this.height = height;} SubType.prototype = Object.create (SuperType.prototype); SubType.prototype.constructor = SubType;SubType.prototype.method = function () {return 1;} var instance = new SubType ('teren',18180)

The above is one of the most commonly used design patterns for implementing inheritance between multiple classes

The advantages and disadvantages of using Object.create (SuperType.prototype) are:

Pros: the ability to create a new SuperType.prototype object assigned to SubType.prototype and modify the SubType.prototype without affecting the original constructor SuperType.prototype

Disadvantages: although the prototype value of the subclass is the same as the prototype value of the parent class, the memory is different, thus cutting off the type between the subclass and the parent class

You can also use SubType.prototype = new SuperType () to achieve the same effect, with the advantages and disadvantages of:

Advantages: ability to reflect the inheritance relationship between subclasses and parents

Disadvantages: subclasses have private properties of the parent class

Therefore, the Object.create () method is generally used when actually implementing the prototype chain, while the new SuperType () method is used when understanding the prototype chain.

3.3 methods related to prototype objects

Traversal object property method

Object.keys () and Object.getOwnPropertyNames () are used to traverse the object itself instead of inheriting property names, returning an array where Object.keys () returns only enumerable properties

In is used to check whether an object has a property. It does not distinguish whether the property is a property of the object itself or an inherited property

For...in is used to traverse all enumerable properties of an object (whether own or inherited)

If you only traverse your own properties, you can use the following code:

For (var key in instance) {if (instance.hasOwnProperty (key)) {console.log (key)}}

A method to determine whether an attribute is itself or not

Object.prototype.hasOwnProperty () returns a Boolean value that determines whether a property is defined on the object itself or on the prototype chain

Methods to set and get the prototype object of an instance object

Object.getPropertyOf () returns a prototype object of an instance object

Object.setPropertyOf (obj,prototype) can pass two parameters, the first is an existing parameter, and the second is a prototype object

Determine whether an object is a prototype object of another object.

Object.prototype.isPrototypeOf () is used to determine whether one object is the prototype of another object.

Summary

After reading through this article, we can know:

Object-oriented programming is a mode of thinking, which regards everything in the world as a collection of objects, and the operation of the world is the result of the division and cooperation of objects; mapping to programming is to write objects (modules) with specific functions, and organically integrate them to make the program work.

From the point of view of data characteristics, an object is a collection of unordered key-value pairs, and the properties of an object have two characteristics-- data properties and accessor characteristics.

Different ways of creating objects can be called design patterns. This article briefly explains singleton pattern, factory pattern, constructor pattern, prototype pattern, mixed pattern and so on.

From the object-oriented point of view, the object can be said to be the abstraction of real things, and the class is the abstraction of the object.

Each function has a prototype object prototype, which not only deploys shared properties and methods of specific types of instances, but also is the key to JavaScript implementation inheritance.

The prototype prototype object has a constructor property that points to the function pointer where prototype is located.

Whenever an instance is created using the constructor, the instance contains an internal property _ _ proto__ that points to the prototype object of the constructor, thus achieving simple inheritance

When A constructor is an instance of B constructor, a prototype chain is formed, that is,

The _ _ proto__ of the A constructor instance object C points to the prototype object of the A constructor, the _ _ proto__ of the prototype,A constructor prototype points to the prototype object of the B constructor, the _ _ proto__ of the prototype,B constructor prototype points to the _ _ proto__ of the prototype,Function prototype of the Function constructor, and points to the prototype of Object.

Methods related to prototype objects include: Object.keys () and Object.getPropertyNames (), for...in methods, Object.getPrototypeOf () and Object.setPrototypeOf () methods, Object.prototype.hasOwnProperty () and Object.prototype.isPrototypeOf () methods

At this point, the study on "the method of creating objects by JavaScript and the introduction of examples of various patterns" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Development

Wechat

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

12
Report