Home>

Then above"Detailed explanation of JavaScript based on object-oriented object creation (1)"keep studing.

4. Prototype method

Every function we create has a prototype property, which is an object,Its purpose is to contain properties and methods that can be shared by all instances of a particular type.Logically, it can be understood as follows:prototype is the prototype object of the object created by the constructor.The advantage of using a prototype is that all object instances can share the properties and methods it contains.That is,It is not necessary to define object information in the constructor,Instead, add this information directly to the prototype.

The prototype method uses the prototype property of the object, which can be considered as the prototype on which the new object is created.Here, first set the function name with an empty constructor.Then all properties and methods are directly assigned to the prototype property. I rewritten the previous example,code show as below:

function car () {};
//Assign all properties to the prototype property
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 () + "<br />");//Output:blue
document.write (car2.showcolor ());//Output:blue

In this code,First define the constructor car () without any code in it.The next few lines of code,Define properties of the car object by adding properties to the prototype property of the car.When new car () is called, all the properties of the prototype are immediately assigned to the object to be created,This means that all car instances store pointers to the showcolor () function.Semantically,All attributes appear to belong to one object,Therefore, the problems existing in the previous factory mode and constructor mode are solved.

Also, using this approach,You can also use the instanceof operator to check the type of the object pointed to by a given variable:

<span>document.write (car1 instanceof car);//Output:true</span>

The prototype approach looks like a good solution.Regrettably,It's not satisfactory.First, this constructor has no parameters.Using the prototype approach,You cannot initialize the value of a property by passing parameters to the constructor,Because the color attributes of car1 and car2 are equal to "blue", the doors attribute is equal to 4, and the mpg attribute is equal to 25. This means that the property's default value must be changed after the object is created,This is annoying.But it's not over.The real problem arises when the property points to an object,Instead of functions.Function sharing does not cause problems,Objects are rarely shared by multiple instances.Consider the following example:

function car () {};//Define an empty constructor,And cannot pass parameters
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 + "<br />");//Output:mike, john, bill
document.write (car2.drivers);//Output:mike, john, bill

In the above code,The properties drivers are pointers to array objects,The array contains two names "mike" and "john". Since drivers are reference values,Both instances of car point to the same array.This means that adding the value "bill" to car1.drivers can also be seen in car2.drivers.Output either of these two pointers,The result is the display string "mike, john, bill". With so many issues when creating objects,You will definitely think,Is there a reasonable way to create objects?The answer is yes,A combination of constructor and prototype methods is required.

5.Hybrid constructor/prototype (recommended)

Mixing constructor and prototype methods,Objects can be created just like any other programming language.The concept is very simple,That is, all non-functional attributes of an object are defined using a constructor,Defining function properties (methods) of objects in a prototype way. As a result, all functions are created only once,And each object has its own instance of the object properties.We rewrite the previous example,code show as below:

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", 4,23);
var car2=new car ("blue", 3,25);
car1.drivers.push ("bill");
document.write (car1.drivers + "<br />");//Output:mike, john, bill
documnet.write (car2.drivers);//Output:mike, john

Now it's more like creating general objects.All non-function attributes are created in the constructor,This means that you can use the constructor's parameters to assign properties to default values ​​again.Because only one instance of the showcolor () function is created,So there is no memory waste.In addition, adding "bill" to the drivers array of car1 will not affect the array of car2, so when outputting the values ​​of these arrays,car1.drivers shows "mike, john, bill" and car2.drivers shows "mike, john". Because of the prototype approach,So you can still use the instanceof operator to determine the type of an object.

This method is the main method used by ecmascript,It has the characteristics of other ways,Without their side effects.However, some developers still feel that this method is not perfect.

6.Dynamic prototype methodFor developers accustomed to using other languages,Using a mixed constructor/prototype approach feels less harmonious.After all, when defining a class,Most object-oriented languages ​​have a visual encapsulation of properties and methods.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 packs all the properties and methods of the car class well.So when you see this code, you know what it does.It defines the information of an object.Critics of the mixed constructor/prototype approach argue thatFind properties inside the constructor,It is illogical to find a way outside of it.So they designed a dynamic prototype approach,To provide a more friendly coding style.

The basic idea of ​​the dynamic prototype method is the same as the hybrid constructor/prototype approach,That is, defining non-function attributes within the constructor,Function attributes are defined using prototype attributes.The only difference is the location of the method assigned to the object.Here is the car 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, it means that no method has been added to the prototype of the car
 if (typeof car._initialized == "undefined") {
   car.prototype.showcolor=function () {
    return this.color;
   };
   car._initialized=true;//Set to true, no need to add methods for prototype
 }
}
var car1=new car ("red", 4,23);//Generate a car object
var car2=new car ("blue", 3,25);
car1.drivers.push ("bill");//Add an element to the drivers property of the car1 object instance
document.write (car1.drivers + "<br />");//Output:mike, john, bill
document.write (car2.drivers);//Output:mike, john

This constructor does not change until it checks whether typeof car._initialize is equal to "undefined".This line of code is the most important part of the dynamic prototype method.If this value is undefined,The constructor will continue to define the object's methods in a prototype way,Then set car._initialized to true. If this value is defined (when its value is true, the value of typeof is boolean), then the method is no longer created.in short,This method uses the flag (_initialized) to determine if any methods have been assigned to the prototype.This method is created and assigned only once,Traditional oop developers will be happy to find thatThis code looks more like a class definition in other languages.

Which way should we use?As mentioned earlier,The most widely used currently is the hybrid constructor/prototype approach.In addition, dynamic prototyping is also very popular,Functionally equivalent to the constructor/prototype approach.Either way can be used.But don't use the classic constructor or prototype method alone,Because this will introduce problems to the code.In short, js is an object-oriented client-side scripting language.When we learn its object-oriented technology, we should pay attention to the difference between js and other rigorous programming languages.Also a reasonable way to use js to create objects properly,It is recommended to use a mixture of constructor and prototype methods to create object instances.This can avoid many unnecessary hassles.

  • Previous How does JQuery pass and parse data in Json format under the SpringMVC framework
  • Next Restful passing array parameters and annotations