How to create an object based on object-oriented JavaScript (2) _ javascript skills

Source: Internet
Author: User
This article mainly introduces how to create an object based on object-oriented JavaScript, detailed analysis of the object-oriented prototype and other comprehensive methods. If you are interested, refer to the previous section. Details about how to create an object based on object-oriented JavaScript (1)Continue learning.

4. Prototype
Each function we create has a prototype attribute. This attribute is an object and its purpose is to include attributes and methods that can be shared by all instances of a specific type. Logically, we can understand that prototypt uses the constructor to create the prototype object of the object. The advantage of using a prototype is that all object instances can share its attributes and methods. That is to say, you do not need to define the object information in the constructor, but directly add the information to the prototype.
The prototype method uses the prototype attribute of the object to create a prototype on which the object depends. Here, we first use an empty constructor to set the function name. Then all attributes and methods are directly assigned the prototype attribute. I have rewritten the previous example and the code is as follows:

Function Car () {}; // assign all attribute methods to the prototype attribute Car. prototype. color = "blue"; Car. prototype. doors = 4; Car. prototype. mpg = 25; Car. prototype. showColor = function () {return this. color ;}; var Car1 = new Car (); var Car2 = new Car (); document. write (Car1.showColor () +"
"); // Output: blue document. write (Car2.showColor (); // output: blue

In this Code, first define the constructor Car (), without any code. The following code defines the attributes of a Car object by adding attributes to the prototype attribute of the Car. When new Car () is called, all attributes of the prototype are immediately assigned to the object to be created, meaning that all the Car instances store pointers to the showColor () function. In terms of semantics, all attributes seem to belong to one object. Therefore, the existing factory method and constructor method are solved.
In addition, you can use the instanceof operator to check the type of the object to which a given variable points:

The Code is as follows:

Document. write (Car1 instanceof Car); // output: true


The prototype seems to be a good solution. Unfortunately, it is not satisfactory. First, this constructor has no parameters. Using the prototype method, you cannot pass parameters to the constructor to initialize the attribute value, because the color attributes of Car1 and Car2 are equal to "blue", and the doors attributes are equal to 4, all mpg attributes are equal to 25. This means that the default attribute value can be changed only after the object is created. This is annoying, but it is not complete yet. The real problem occurs when the property points to an object rather than a function. Function sharing does not cause problems, but objects are rarely shared by multiple instances. Consider the following example:

Function Car () {}; // defines an empty constructor and cannot pass the parameter Car. prototype. color = "blue"; Car. prototype. doors = 4; Car. prototype. mpg = 25; Car. prototype. drivers = new Array ("Mike", "John"); Car. prototype. showColor = function () {return this. color ;}; var Car1 = new Car (); var Car2 = new Car (); Car1.drivers. push ("Bill"); document. write (Car1.drivers +"
"); // Output: Mike, John, Bill document. write (Car2.drivers); // output: Mike, John, Bill

In the code above, the attribute drivers is a pointer to an Array object, which contains two names: "Mike" and "John ". Because drivers is a reference value, both instances of Car point to the same array. This means to add the value "Bill" to Car1.drivers, which can also be seen in Car2.drivers. Output any of the two pointers. The result is the string "Mike, John, Bill ". Since there are so many problems when creating objects, you will surely wonder if there is a reasonable method to create objects? The answer is yes. constructor and prototype must be used together.
5. Mixed constructor/prototype (recommended)
Using constructor and prototype together, you can create objects just like using other programming languages. This concept is very simple, that is, using constructors to define all non-function attributes of an object and using prototype to define the function attributes (methods) of an object ). The result is that all functions are created only once, and each object has its own object attribute instance. We have rewritten the previous example. The Code is as follows:

Function Car (Color, Doors, Mpg) {this. color = Color; this. doors = Doors; this. mpg = Mpg; this. drivers = new Array ("Mike", "John") ;}; Car. prototype. showColor = function () {return this. color ;}; var Car1 = new Car ("red",); var Car2 = new Car ("blue",); Car1.drivers. push ("Bill"); document. write (Car1.drivers +"
"); // Output: Mike, John, Bill w.net. write (Car2.drivers); // output: Mike, John

Now it is more like creating a common object. All the non-function attributes are created in the constructor, which means that the default values can be assigned to the constructor parameters. Because only one instance of the showColor () function is created, there is no memory waste. In addition, adding the "Bill" value to the drivers array of Car1 does not affect the Car2 array. Therefore, when outputting the values of these arrays, Car1.drivers displays "Mike, John, Bill ", car2.drivers shows "Mike, John ". Because the prototype method is used, the instanceof operator can still be used to determine the object type.
This method is the main method adopted by ECMAScript. It has other features but has no side effects. However, some developers still feel that this method is not perfect.
6. Dynamic Prototype
Developers who are used to other languages feel less harmonious when using a hybrid constructor/prototype. After all, most object-oriented languages visually encapsulate attributes and methods when defining classes. Consider the following Java classes:

class Car {  public String color = "blue";  public int doors = 4;  public int mpg = 25;  public Car(String color, int doors, int mpg) {   this.color = color;   this.doors = doors;   this.mpg = mpg;  }  public void showColor() {   System.out.println(color);  } } 

Java well packages all the attributes and methods of the Car class. Therefore, when you see this code, you will know what functions it will implement and define the information of an object. People who criticize the mixed constructor/prototype think that finding properties inside the constructor and finding methods outside of the constructor is not logical. Therefore, they have designed a dynamic prototype method to provide a more friendly encoding style.
The basic idea of the dynamic prototype method is the same as that of the mixed constructor/prototype method. That is, the non-function attributes are defined in the constructor, while the function attributes are defined using the prototype attributes. The only difference is that the location of the object method is assigned. Here is the Car that is rewritten using the dynamic prototype method:

Function Car (Color, Doors, Mpg) {this. color = Color; this. doors = Doors; this. mpg = Mpg; this. drivers = new Array ("Mike", "John"); // if _ initialized in the Car object is undefined, the method if (typeof Car) is not added to the Car prototype. _ initialized = "undefined") {Car. prototype. showColor = function () {return this. color;}; Car. _ initialized = true; // if it is set to true, you do not have to add a method for prototype} var Car1 = new Car ("red ); // generate a Car object var Car2 = new Car ("blue", 3,25); Car1.drivers. push ("Bill"); // Add an element document to the drivers attribute of the Car1 object instance. write (Car1.drivers +"
"); // Output: Mike, John, Bill document. write (Car2.drivers); // output: Mike, John

This constructor remains unchanged until the typeof Car. _ initialize check is equal to "undefined. This line of code is the most important part of the dynamic prototype method. If this value is not defined, the constructor will continue to define the object method in prototype mode, and then set Car. _ initialized to true. If this value is defined (when its value is true, the value of typeof is Boolean), this method will not be created. In short, this method uses the sign (_ initialized) to determine whether any method has been granted to the prototype. This method is created and assigned only once. Traditional OOP developers are happy to find that this code looks more like a class definition in other languages.
What method should we use?
As mentioned above, the most widely used method is the hybrid constructor/prototype method. In addition, the dynamic prototype method is also very popular, and its function is equivalent to the constructor/prototype method. Either of the two methods can be used. However, do not use the classic constructor or prototype alone, because this will introduce problems to the code. In short, JS is an object-oriented client scripting language. When learning its object-oriented technology, we should pay attention to the differences between JS and other highly rigorous programming languages. We also recommend that you use a mix of constructor and prototype methods to create an object instance. This can avoid unnecessary troubles.

The above is all the content of JavaScript Object creation based on object-oriented, and I hope it will be helpful for you to learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.