Detailed JavaScript based object-oriented object creation (2) _javascript tips

Source: Internet
Author: User
Tags class definition mixed

And then , "Detailed JavaScript is based on object-oriented creation object (1)" to continue learning.

4. Prototype mode
Each function we create has a prototype (prototype) attribute, which is an object that is intended to contain properties and methods that can be shared by all instances of a particular type. Logically you can understand this: the prototype object of the object that Prototypt created with the constructor. The advantage of using prototypes is that all object instances can share the properties and methods it contains. That is, you do not have to define object information in the constructor, but instead add that information directly to the prototype.
The prototype method utilizes the prototype attribute of the object and can be viewed as the prototype on which the new object is created. Here, first use the empty constructor to set the function name. All of the properties and methods are then given directly to the prototype attribute. I rewrote the previous example with the following code:

function car () {}; 
Assigns all attribute methods to the prototype property 
Car.prototype.color = "Blue"; 
Car.prototype.doors = 4; 
Car.prototype.mpg =; 
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, you first define the constructor car (), which has no code. The next few lines of code define the properties of the car object by adding properties to the car's prototype property. When you call new car (), all the properties of the stereotype are immediately given to the object to be created, meaning that all car instances hold pointers to the Showcolor () function. Semantically, all attributes seem to belong to an object, thus resolving the problems of the previous factory approach and constructor approach.
In addition, in this way, you can also use the instanceof operator to check the type of object that the given variable points to:

Copy Code code as follows:
<span style= "FONT-SIZE:18PX;"    >document.write (Car1 instanceof car); Output:true</span>

The prototype approach looks like a good solution. Sadly, it's not as satisfactory. First, this constructor has no parameters. Using prototypes, you cannot initialize the value of a property by passing arguments to the constructor, because the color property of both Car1 and Car2 equals "blue," and the Doors property equals the 4,mpg property equals 25. This means that you must create an object before you can change the default value of the property, which is annoying, but not yet finished. The real problem arises when the attribute points to an object, not 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 arguments 
Car.prototype.color = "Blue"; 
Car.prototype.doors = 4; 
Car.prototype.mpg =; 
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 code above, the property drivers is a pointer to the array object that contains two names, "Mike" and "John." Since drivers is a reference value, all two instances of the car point to the same array. This means adding the value "Bill" to Car1.drivers, which can be seen in car2.drivers. Outputs any of these two pointers, resulting in the display string "Mike,john,bill". Because there are so many problems creating objects, you're going to wonder if there's a reasonable way to create objects? The answer is yes, you need to use constructors and prototypes together.
5, mixed constructor/prototype mode (recommended)
mixed with constructors and prototypes, you can create objects just as you would with other programming languages. The concept is very simple, that is, to define all the non function properties of an object with a constructor, and to define the object's function properties (methods) in a prototype manner. As a result, all functions are created only once, and each object has its own instance of an object attribute. We rewrote the previous example with the following code:

 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 

It's more like creating a generic object now. All of the non function properties are created in the constructor, which means that the property defaults can be given to the constructor's arguments. Because only one instance of the Showcolor () function is created, there is no memory waste. In addition, adding "Bill" values to the CAR1 drivers array does not affect the CAR2 array, so when outputting the values of these arrays, Car1.drivers displays "Mike,john,bill" and Car2.drivers shows "Mike, John ". Because of the prototype approach, the instanceof operator can still be used to determine the object's type.
This approach is the main method used by ECMAScript, which has other characteristics, but without their side effects. However, some developers still find this method less than perfect.
6. Dynamic Prototyping Mode
for developers who are accustomed to using other languages, it feels less harmonious to use a mixed constructor/prototyping approach. After all, when defining classes, most object-oriented languages visually encapsulate properties and methods. Consider the following Java class:

Class Car {public 
 String color = "Blue"; 
 public int doors = 4; 
 public int mpg =; 
 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 nicely packs all the properties and methods of the car class, so seeing this code knows what it's going to do, and it defines an object's information. Critics of the hybrid constructor/archetype approach argue that it is illogical to look for attributes within the constructor and find methods outside of them. As a result, they designed a dynamic prototyping approach to provide a more user-friendly coding style.
The basic idea of a dynamic prototyping method is the same as a mixed constructor/prototype approach, that is, to define the non function attribute within the constructor, and the function property to use the stereotype attribute definition. The only difference is where the object method is assigned. The following is the car that was overridden with the dynamic prototyping method:

function car (color,doors,mpg) { 
 this.color = Color; 
 this.doors = doors; 
 This.mpg = mpg; 
 This.drivers = new Array ("Mike", "John"); 
 If the _initialized in the car object is undefined, it indicates that no method is added for the car's prototype if 
 (typeof car._initialized = = "undefined") { 
   Car.prototype.showColor = function () {return 
    this.color; 
   }; 
   Car._initialized = true; Set to True, no more methods are added 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 
document.write (car1.drivers+ "<br/>") to the drivers property of the Car1 object instance; Output: Mike,john,bill 
document.write (car2.drivers);//output: Mike,john 

This constructor does not change until you check that typeof car._initialize is equal to "undefined". This line of code is the most important part of the dynamic prototyping approach. If this value is undefined, the constructor will continue to define the object's methods in a prototype manner and then set car._initialized to True. If the value is defined (its value is true, the value of typeof is Boolean), the method is no longer created. In short, the method uses flags (_initialized) to determine whether any method has been given to the prototype. The method creates and assigns values only once, and traditional OOP developers are pleased to see that the code looks more like a class definition in other languages.
Which way should we adopt?
As mentioned earlier, the most widely used current is the hybrid constructor/prototyping approach. In addition, dynamic prototyping is also popular and functionally equivalent to the constructor/prototype approach. Either of these two approaches can be used. However, do not use the classic constructor or prototyping alone, as this can introduce problems to your code. In short, JS is based on object-oriented client-side scripting language, we learn its object-oriented technology in the time to pay attention to JS and other rigorous program language differences. It is also a reasonable way to use JS to create objects correctly, and it is recommended to create object instances in a mixed way using constructors and prototypes. This will avoid a lot of unnecessary trouble.

The above is JavaScript based on object-oriented creation of the entire content of objects, I hope to help you 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.