I want to learn about the eight methods for creating objects (classes) in javascript. Each method has a detailed introduction. Do not miss this article if you do not know how to create objects in javascript. 8. The javascript method for creating objects (classes) is introduced to you by Yi. I hope you will like it.
1. Create an Object using the Object constructor
The following code creates a person object and prints the property value of Name in two ways.
var person = new Object(); person.name="kevin"; person.age=31; alert(person.name); alert(person["name"])
Another manifestation of the above statement is to use the object literal to create an object. Do not be surprised that person ["5"] is legal here; in addition, the brackets can be used to separate fields with spaces, such as person ["my age"].
var person = { name:"Kevin", age:31, 5:"Test" }; alert(person.name); alert(person["5"]);
Although the Object constructor or Object literal can be used to create a single Object, there is an obvious disadvantage in these methods: using the same interface to create many objects will produce a lot of repeated code. To solve this problem, people began to use a variant of the factory model.
2. Factory Model
The factory model is a well-known design pattern in the software engineering field. This pattern abstracts the process of creating a specific object. Considering that the class cannot be created in ECMAScript, developers have invented a function that encapsulates the details of creating objects with specific interfaces, as shown in the following example.
function createPerson(name, age, job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function(){ alert(this.name); }; return o;}var person1 = createPerson("Nicholas", 29, "Software Engineer");var person2 = createPerson("Greg", 27, "Doctor");
Although the factory mode solves the problem of creating multiple similar objects, it does not solve the problem of Object Recognition (that is, how to know the type of an object ). With JavaScript
Another new model emerged.
3. constructor Mode
Constructor like Object and Array will automatically appear in the execution environment during runtime. In addition, you can create custom constructors to define attributes and methods of custom object types. For example, you can use the constructor mode to rewrite the previous example as follows.
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name);};}var person1 = new Person("Nicholas", 29, "Software Engineer");var person2 = new Person("Greg", 27, "Doctor");
In this example, the Person () function replaces the createPerson () function. We noticed that in addition to the Code in Person () and createPerson (), there are also the following differences:
- No explicit object creation;
- Attributes and methods are directly assigned to this object;
- No return statement.
To create a new instance of Person, you must use the new operator. Calling the constructor in this way actually goes through the following:4 steps:
(1) create a new object;
(2) Assign the scope of the constructor to the new object (so this points to the new object );
(3) execute the code in the constructor (add attributes for the new object );
(4) return the new object.
At the end of the previous example, person1 and person2 respectively save a different instance of Person. Both objects have a constructor (constructor) attribute, which points to Person, as shown below.
alert(person1.constructor == Person); //truealert(person2.constructor == Person); //true
The constructor attribute of an object is initially used to identify the object type. However, the instanceof operator must be more reliable when it comes to object types. All objects created in this example are both Object instances and Person instances, which can be verified by the instanceof operator.
alert(person1 instanceof Object); //truealert(person1 instanceof Person); //truealert(person2 instanceof Object); //truealert(person2 instanceof Person); //true
Creating a custom constructor means that its instance can be identified as a specific type in the future. This is where the constructor mode is better than the factory mode. In this example, person1 and person2 are both Object instances because all objects are inherited from objects.
Constructor Problems
Although the constructor mode is easy to use, it is not a disadvantage. The main problem with using constructors is that each method must be re-created on each instance.
The functions in ECMAScript are objects. Therefore, each function is defined, that is, an object is instantiated. Logically, the constructor can be defined in this way.
Function Person (name, age, job) {this. name = name; this. age = age; this. job = job; this. sayName = new Function ("alert (this. name) "); // logically equivalent to the declarative function}
From this perspective, constructor makes it easier to understand the nature of each Person instance that contains a different Function instance (to display the name attribute. Note: creating a Function in this way will lead to resolution of different scopes and identifiers, but the mechanism for creating a new Function instance is still the same. Therefore, functions of the same name on different instances are not equal. The following code proves this.
alert(person1.sayName == person2.sayName); //false
However, it is unnecessary to create two Function instances that complete the same task. Besides, this object does not need to bind the Function to a specific object before executing the code. Therefore, we can solve this problem by moving the function definition to the external part of the constructor as follows.
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.sayName = sayName;}function sayName(){ alert(this.name);}var person1 = new Person("Nicholas", 29, "Software Engineer");var person2 = new Person("Greg", 27, "Doctor");
If the object needs to define many methods, we need to define many global functions. Therefore, the custom reference type is not encapsulated at all. Fortunately, these problems can be solved by using the prototype mode.
4. Prototype
function Person(){}Person.prototype.name = "Nicholas";Person.prototype.age = 29;Person.prototype.job = "Software Engineer";Person.prototype.sayName = function(){ alert(this.name);};var person1 = new Person();person1.sayName(); //"Nicholas"var person2 = new Person();person2.sayName(); //"Nicholas"alert(person1.sayName == person2.sayName); //true
To understand the prototype object, see my other blog: JavaScript prototype details
In the preceding example, you must repeat Person. prototype for each attribute and method. To reduce unnecessary input and better visually encapsulate prototype functions, A more common approach is to overwrite the entire prototype object with a literal volume of all attributes and methods, as shown in the following example.
function Person(){}Person.prototype = { name : "Nicholas", age : 29, job: "Software Engineer", sayName : function () { alert(this.name); }};
In the above Code, we set Person. prototype to be equal to a new object created in the form of an object literally. The final result is the same, but there is an exception: the constructor attribute no longer points to the Person. As mentioned earlier, each time a function is created, its prototype object is created at the same time. This object also automatically obtains the constructor attribute. The syntax we use here completely overwrites the default prototype Object. Therefore, the constructor attribute becomes the constructor attribute of the new Object (pointing to the Object constructor) and does not point to the Person function. At this time, although the instanceof operator can return the correct results, the constructor can no longer determine the object type, as shown below.
var friend = new Person();alert(friend instanceof Object); //truealert(friend instanceof Person); //truealert(friend.constructor == Person); //falsealert(friend.constructor == Object); //true
Here, the instanceof operator test Object and Person still returns true, but the constructor attribute is equal to Object rather than Person. If the constructor value is really important, you can set it back to the appropriate value as follows.
function Person(){} Person.prototype = { constructor : Person, name : "Nicholas", age : 29, job: "Software Engineer", sayName : function () { alert(this.name); }};
Note that the pointer in the instance only points to the prototype, not the constructor.
The problem with prototype objects: Prototype is not a disadvantage. First, it omits the process of passing initialization parameters for the constructor. As a result, all instances will obtain the same attribute value by default. Although this may cause some inconvenience to some extent, it is not the biggest problem of the prototype. The biggest problem with the prototype model is its shared nature.
function Person(){}Person.prototype = { constructor: Person, name : "Nicholas", age : 29, job : "Software Engineer", friends : ["Shelby", "Court"], sayName : function () { alert(this.name); }};var person1 = new Person();var person2 = new Person();person1.friends.push("Van");alert(person1.friends); //"Shelby,Court,Van"alert(person2.friends); //"Shelby,Court,Van"alert(person1.friends === person2.friends); //true
5. Use the constructor mode and prototype mode in combination (most commonly used)
The most common way to create a custom type is to combine the constructor mode and the prototype mode. The constructor mode is used to define instance attributes, while the prototype mode is used to define methods and shared attributes. As a result, each instance has its own copy of the Instance attribute, but it also shares the reference to the method, saving the memory to the maximum extent. In addition, this mixed mode also supports passing parameters to the constructor.
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.friends = ["Shelby", "Court"];}Person.prototype = { constructor : Person, sayName : function(){ alert(this.name); }}var person1 = new Person("Nicholas", 29, "Software Engineer");var person2 = new Person("Greg", 27, "Doctor");person1.friends.push("Van");alert(person1.friends); //"Shelby,Count,Van"alert(person2.friends); //"Shelby,Count"alert(person1.friends === person2.friends); //falsealert(person1.sayName === person2.sayName); //true
6. Dynamic Prototype
Developers with experience in other OO languages may be very confused when they see independent constructors and prototypes. The dynamic prototype is a solution dedicated to solving this problem. It encapsulates all information in constructors, by initializing the prototype in the constructor (only when necessary), the advantage of using the constructor and prototype at the same time is maintained. In other words, you can determine whether to initialize the prototype by checking whether a method that should exist is valid. Let's look at an example.
Function Person (name, age, job) {// attribute this. name = name; this. age = age; this. job = job; // method ------------------------------------------------- if (typeof this. sayName! = "Function") {Person. prototype. sayName = function () {alert (this. name) ;}}----------------------------------------------} var friend = new Person ("Nicholas", 29, "Software Engineer"); friend. sayName ();
7. Parasitic constructor Mode
In general, the parasitic constructor mode can be used if none of the preceding modes are applicable. The basic idea of this mode is to create a function. The function is only used to encapsulate the code for creating an object and then return the newly created object. But on the surface, this function looks like a typical constructor. The following is an example.
function Person(name, age, job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function(){ alert(this.name); }; return o;}var friend = new Person("Nicholas", 29, "Software Engineer");friend.sayName(); //"Nicholas"
In this example, the Person function creates a new object, initializes the object with the corresponding attributes and methods, and then returns the object. In addition to using the new operator and calling the wrapped function constructor, this mode is exactly the same as the factory mode. If no value is returned, the constructor returns a new object instance by default.
8. Safe Construction of function Modes
A secure object refers to an object that does not have a public attribute and does not reference this in its method. Secure objects are best suited to some secure environments (this and new are not allowed in these environments), or to prevent data from being changed by other applications (such as Mashup programs. The safe constructor follows a pattern similar to the parasitic constructor, but there are two differences: first, the instance method of the newly created object does not reference this; second, the constructor is not called using the new operator. According to the requirements of the secure constructor, you can rewrite the previous Person constructor as follows.
Function Person (name, age, job) {// create the Object var o = new Object () to be returned; // you can define private variables and functions here // Add method o. sayName = function () {alert (name) ;}; // return object return o ;}
Have you learned the above eight methods for creating objects (classes) using javascript? I hope it will be helpful to you.