Javascript Object-Oriented Analysis-object Creation

Source: Internet
Author: User
First, we will introduce the default mode that is most widely used in ecmascript and has the highest degree of consistency. 1. Combined use of constructors and prototypes
 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 ('nocholas ', 29, 'Software engineer' ); Alert (person1.friends );  //  "Shelby, Count, Van" Person1.sayname (); //  "Nocholas" 

the instance attributes are defined in the constructor, the constructor and sayname () attributes shared by all instances are in the prototype. Defined.

The constructor attribute always points to the constructor that creates the current object,Remember this. Constructor attributes

2. constructor Mode
 Function Person (name, age, job ){  This . Name = Name;  This . Age = Age;  This . Job = Job;  This . Sayname: Function  () {Alert (  This  . Name );}}  VaR Person1 = New Person ('nocholas ', 29, 'Software engineer' );  VaR Person2 = New Person ('greg ', 27, 'Doctor' ); Person1.sayname ();  //  "Nocholas" Person1.sayname (); //  "Greg" 

The constructor should always start with an uppercase letter.

Features: This method does not explicitly create an object; it directly assigns attributes and methods to this object; there is no return value.

To create a new instance of person, you must use the new operator. Calling the constructor in this way actually goes through the following four steps:

(1) create a new object

(2) Assign the scope of the constructor to the object (so this points to this new object)

(3) executeCode(Add attributes for this new object)

(4) return the new object

Let's check the object type.

 alert (person1  instanceof  Object); ///   true  alert (person1  instanceof  person); ///   true  alert (person2  instanceof  Object); ///   true  alert (person2  instanceof  person); ///   true  

In this example, both person1 and person2 are person instances, and all objects are inherited from objects.

Constructor mode disadvantages:

the main problem with using constructors is that each method must be re-created on each instance. In the previous example, person1 and person2 both have a method named sayname, but the two methods are not instances of the same function. Functions in ecmascript are objects. Therefore, each defined function is to instantiate an object. Logically, the constructor can also be defined as follows:

FunctionPerson (name, age, job ){This. Name =Name;This. Age =Age;This. Job =Job;This. Sayname =NewFunction () {alert (This. Name );}}

From this perspective, the constructor is easier to understand that each person instance contains the essence of a different function instance. As mentioned above, these two functions are not equal,

 
Alert (person1.sayname () = person2.sayname ())//False

There is no reason to create methods that implement the same function multiple times, especially when there are a large number of methods, even though the following methods can be used to avoid multiple creation:

FunctionPerson (name, age, job ){This. Name =Name;This. Age =Age;This. Job =Job;This. Sayname =Sayname ;}FunctionSayname () {alert (This. Name );}

We create the global function sayname and set the attributes inside the constructor to the sayname function that is equal to the global value. Because sayname contains a pointer to the function, the person1 and person2 objects share the functions in the global scope, which solves the problem of two functions doing one thing together, however, in this way, the sayname function in the global scope is called only for the object instantiated by person, so that the global scope is somewhat named.

What is even more unacceptable is that many functions need to be defined when many methods are to be defined, so our custom classes become unencapsulated. Fortunately, these problems can be solved through the prototype mode.

3. prototype mode

Simple understanding: each function we create has a prototype attribute, which is an object. Its purpose is to allow all instances to share its attributes and methods. In other words, you do not need to define the object information in the constructor, but you can add the information directly to the prototype object, as shown below:

 Function  Person () {} person. Prototype. Name = "Nicolas" ; Proson. Prototype. Age = 29 ; Person. Prototype. sayname = Function  () {Alert (  This  . Name );}  VaR Person1 = New Person (); person1.sayname ();  //  "Nicolas"  VaR Person2 = New  Person (); person2.sayname ();  //  "Nicolas"  Alert (person1.sayname = Person2.sayname ); //  True 

We add the sayname () method and all attributes directly to the prototype attribute of person, and the constructor becomes an empty function. Even so, we can still call the constructor to create a new object, the new object also has the same implementation and method. The attributes and methods of the new object are shared by all instances.

Next we will understand the working principle of the prototype model, which is a little abstract, but it is the core part of JS object-oriented programming. It is very important to understand it. Read it several times:

Understanding prototype)

Every JavaScript Object (except null) is associated with another object. The "other" object is a prototype that we are familiar with, and each object inherits attributes from the prototype.

Whenever a new function is created, a prototype attribute is created for the function based on a specific set of rules. We can add attributes and methods for the prototype. By default, the prototype attribute will automatically obtain a constructor attribute. The constructor attribute always points to the constructor that creates the current object. By default, it points to the function itself. We do not need to go into the constructor.

  function   person (name, age, job) {  This . name =  name;   This . age =  age;   This . task =  job;   This . friends = ["Shelby", "court" ];} person. prototype. sayname  =  function   () {alert (  This  . name);} console. log (person. prototype. constructor == person); ///   true  

In additionEach object will Initialize an attribute inside it, namely _ PROTO __,_ PROTO _ point to the pertotype of the parent object of the current objectWhen we access the attribute of an object, if this attribute does not exist inside the object, it will go to _ PROTO _ to find this attribute, the _ PROTO _ has its own _ PROTO __, so we keep looking for it, that is, the concept of prototype chain that we usually call.

 

 Function  Person (name, age, job ){  This . Namee = Name;  This . Age = Age;  This . Job = Job;} person. Prototype. sayname = Function () {Alert (  This  . Name);} console. Log (person. _ PROTO __ === Function. Prototype ); //  True from function; Console. Log ("******************" ); Console. Log (function. Prototype. _ PROTO __ === Object. Prototype); console. Log (object. Prototype. _ PROTO __ === Null ); //  True 

 

The starting point of the prototype chain is that the object. Prototype object. Prototype contains built-in methods such as tostring () and valueof (). This is also the same name method of various data types, which is actually inherited from this.

Take a look at the following. Note that prototype and _ PROTO _ are distinguished:

A common function person () {} has both prototype and _ PROTO __. Person. prototype contains all attributes and methods that will be passed to the son after the person has been owned. At the beginning, only one constructor attribute can be included and the person can be freely added. prototype. familyname = "Chen"; person. prototype. skill = "Girl ";

Person. _ PROTO _ points to the father's prototype function of person. prototype. Obviously, only one constructor attribute is included by default if function has occurred. prototype. car = "Rolls-Royce", Dad has a Rolls-Royce car, so the console. log (person. car) // The Rolls-Royce person also inherits.

The instantiated object person1 = new person (); is console. Log (person. Prototype) without prototype; // undefined. The same applies to other object types.

VaRArr =NewArray ();VaRFun =NewFunction ();VaROBJ =NewObject (); console. Log (ARR. Prototype)//UndefinedConsole. Log (fun. Prototype)//UndefinedConsole. Log (obj. Prototype)//Undefined

Simpler prototype syntax

If no attribute or method is added in the preceding example, you must repeat person. prototype. To reduce unnecessary input and better visually encapsulate prototype functions, it is common to overwrite the entire prototype object with an object literal that contains all attributes and methods, as shown below:

FunctionPerson () {} person. Prototype={
Constructor: person, Name:"Nicolas", Age:29, Job:"Software Engineer", Sayname:Function() {Alert (This. Name );}}

Questions about prototype objects:

First, it skips the process of passing initialization parameters for the constructor. As a result, all the strengths obtain the same attribute value by default, which may cause some inconvenience to some extent, however, this is not the biggest problem of prototype. The biggest problem of prototype is caused by its shared nature.

All attributes in the prototype are shared by many instances, which is suitable for functions. The attributes that contain the basic values are also justified (by adding an attribute with the same name on the instance, the corresponding attributes in the prototype can be hidden). However, for attributes that contain reference type values, the problem becomes more prominent.

If you are not clear about the value type, seeJavascript value passing Method

Function  Person () {} psrson. Prototype = {Constructor: person, Name: "Nicolas" , Age: "29" , Friends :[ "Shelby", "court" ], Sayname:  Function  () {Alert (  This  . Name );}}  VaR Person1 = New  Person (); VaR Person2 = New  Persin (); person1.friends. Push ( "Van "); //  Add an element to the friends attribute  Alert (person1.friends );  //  ["Shelby", "Court", "Van"] Alert (person2.friends ); //  ["Shelby", "Court", "Van"] Alert (person1.friends === person2.friends ); //  True 

Since the person DS attribute of person is an array and a reference type (object), we modified the array referenced by person1.friends and added a string to the array. Because the Friends array exists in person. prototype, not in person1, so our modifications will affect all instances. If our original intention is to share an array in all instances, this result is acceptable, however, instances generally have all their own attributes, and this problem is precisely why we seldom see that some people use the prototype separately.

The most common method is to use constructor mode and prototype mode in combination described in the beginning. constructor is used to define instance attributes, and prototype 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.

Note: The knowledge points in this article are derived from JavaScript advancedProgramDesign, to learn more about JavaScript object-oriented, you can view it on your own.

If this article is helpful to you, I would like to thank you for your suggestion.

 

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.