JavaScript Constructors and prototype objects

Source: Internet
Author: User
Tags function prototype object object uppercase letter

/*
* @ JavaScript does not have the concept of classes, so base on object creation is different from object-oriented language
* The common methods of object creation and their limitations
* @ Use object or object literal to create objects
* @ Factory Mode Create object
* @ Constructor Mode Create object
* @ Prototype Mode Create object
* @ Construct and prototype blend mode create objects
*/

To create an object using object or literal literals

/* * @ Create an object with object or literal * @ The most basic way to create an object */ // Create a student object, new one var New Object  "easy ""; " // If this method is troublesome, there is a feeling of bad encapsulation, try to create a literal

Object literal method to create an object

/** @ Object literal method to create object * @ disadvantage, cannot repeat*/varStudent ={name:"easy", Age:"a"}//when we want to create the same kind of student1, student2,..., studentn, we have to repeat the above code n timesvarStudent2 ={name:"easy2", Age:"a"}// ...varSTUDENTN ={name:"easyn", Age:"a"}//it's so troublesome and repetitive that there's a lathe that's constantly producing objects like in the Factory.

Factory mode Creation Object

/** @ Factory mode Create Object * @ JS does not have the concept of class, then we might as well use a function to encapsulate the above object creation process to facilitate repeated invocation of * @ at the same time can give a specific interface to initialize the object*/functioncreatestudent (name, Age) {varobj =New Object(); Obj.name=name; Obj.age=age ; returnobj;}varStudent1 = Createstudent ("easy1", 20);varStudent2 = Createstudent ("easy2", 20);// ...varSTUDENTN = Createstudent ("easyn", 20);

This makes it possible to "produce" objects through the createstudent function, which looks perfect, but we not only want the production of "products" to be as continuous as the factory, but also to know what kind of products are produced.

//for example, We also define the Createfruit () function of the "produce" fruit object.functioncreatefruit (name, Color) {varobj =New Object(); Obj.name=name; Obj.color=color; returnobj;}varV1 = createstudent ("easy1", 20);varV2 = Createfruit ("apple","green"); console.log (v1 instanceof createstudent); //falseConsole.log (v2 instanceof createfruit);//falseConsole.log (v1 instanceofObject);//trueConsole.log (v2 instanceofObject);//true//If we use the instanceof operator to detect, they're all object Types.

We want V1 to be the student type, and v2 is the fruit type, so we can use constructors to create objects

/* * @ What is the difference between "constructor" and "normal function"? There is no special syntax for creating constructors, a constructor is a normal function, and the only difference from a normal function is the call method * @ two. for any function, called with the new operator, it is a constructor; Called with the new operator, then it is the normal function * @ Three. by convention, We agree that the constructor name begins with an uppercase letter * @ Four. When you call the constructor with the new operator, you go through 4 stages *   @ 1. Create a new Object *   @ 2. Assigns a constructor to a new object ( Use TIHS to point to the new Object) *   @ 3. Execute the constructor code *   @ 4. Return new Object */ 

Constructor mode Create object

//rewrite the Factory mode function and add a method propertyfunctionStudent (name, Age) { this. Name =name;  this. Age =age ;  this. Alertname =function() {alert ( this. name); }}functionFruit (name, Color) { this. Name =name;  this. color =color;  this. Alertname =function() {alert ( this. name); }}//new objects for student and fruit, respectivelyvarV1 =NewStudent ("easy", 20);varV2 =NewFruit ("apple","green");//This allows you to use the instanceof operator to detect different objects in the above object type areaConsole.log (v1 instanceof Student);//trueConsole.log (v2 instanceof Student);//falseConsole.log (v1 instanceof Fruit);//falseConsole.log (v2 instanceof Fruit);//trueConsole.log (v1 instanceofObject);//trueConsole.log (v2 instanceofObject);//true

This solves the factory pattern cannot distinguish object type, but this is perfect, in js, the function is an object, when we instantiate more than one Strudent object

 var  v1 = new  Student ( "easy1" , 20);  var  v2 =  "easy2" , 20);  //  ...  var  vn =  "easyn" , 20);  //       Console.log (v1.alertname = = v2.alertname); //  

This is undoubtedly a waste of memory, and we know that this object is bound at run time based on the execution environment of the Function. In the global function, the This object is equal to window, and in the object method, this points to the object

//Try moving an object method outside the constructorfunctionStudent (name, Age) { this. Name =name;  this. Age =age ;  this. Alertname =alertname;}functionalertname () {alert ( this. name);}varSTU1 =NewStudent ("easy1", 20);varSTU2 =NewStudent ("easy2", 20);//when Stu1.alert () is called, the This object is bound to STU1 and is defined by the Alertname () function as a global function, so that the Alertname property in the object is set to a pointer to that Global. This global function is shared by STU1 and stu2, which solves the problem of inherent waste .

however, in the way of global functions to solve the problem of internal sharing of objects, after all, not like a good solution, a better solution is through the prototype object pattern to solve

Prototype schema creation Object

/* * Prototype Mode Create Object * @ Function Prototype Object * @ Object instance and prototype Object's Association * @ Create object with prototype model * Limitations of the prototype model creation object */ /* * The prototype object of the function * @ EACH function has a prototype property, which is a pointer to the constructor created by an object * @, which contains properties and methods that can be shared by all instances * @ by default, All prototype objects automatically contain a constructor property, which is also a pointer to the function where prototype is located */* * Object instance and prototype Object's Association * @ When the constructor is called to create a new instance, the inner part of the instance automatically contains a [[Prototype]] property that points to the Constructor's prototype object, which is associated with the prototype object of the instance and constructor instead of the instance and constructor .

Creating objects using a prototype model

/** Create objects using the prototype model * @ Add properties and methods directly to the prototype object*/functionStudent () {}student.prototype.name="easy"; Student.prototype.age= 20; Student.prototype.alertName=function() {alert ( this. name);}varSTU1 =NewStudent ();varSTU2 =NewStudent ();//true both share the same functionConsole.log (stu1.alertname = =stu2.alertname);//We added the name, the age property, and the Alertname method to the prototype object in strudent, but the STU1 and STU2 created did not contain the name, the age property, and the Alertname () method, containing only one [[ prototype]] pointer properties, How do we find the corresponding properties and methods when we call Stu1.name or stu1.alertname?//when we need to read a property of an object, a search is performed, the property is first looked up in that object, and if found, the property is returned, otherwise, to the prototype object pointed to [[prototype]]//see another layer meaning: if an object instance contains a property or method with the same name in the prototype object, that property or method in the object instance masks the same Name property or method in the prototype object, because "the property is first looked up in the object, and if found, returns the property value"

Overriding a prototype object by object literal

function= {    constructor:student,    "easy"    ,     function () {        Alert (this. name);    }} // it is important to note that we are here to recreate an object object with the objects literal, and then point the student prototype pointer to the OBJECT. During the creation of the object, the new constructor property is automatically obtained, which points to the constructor of Object. therefore, in the above code, we added constructor:student to Re-refer to the student Constructor. 

Limitations of prototype model creation objects
The prototype model gives us a lot of convenience in sharing data with object instances, but often different instances will want to have a separate property of their own, and we combine the model of the constructor with the prototype model to have both data sharing and "not sharing"

Constructing and prototyping blending modes creating objects

/** Construct and prototype mixed mode create Object * We combine the advantages of the prototype pattern in sharing method properties and the constructor pattern in instance method properties, creating objects using the following methods * Defining instance properties in a constructor, defining the pattern of shared properties in the prototype, is the most widely used Method. typically, We will use this method to define reference type variables by Default. *///we want each Stu to have its own name and age propertyfunctionStudent (name, Age) { this. Name =name;  this. Age =age ;}//all Stu should share a alertname () methodStudent.prototype ={constructor:student, alertname:function() {alert ( this. name); }}varSTU1 =NewStudent ("Jim", 20);varSTU2 =NewStudent ("Tom"21st); stu1.alertname (); stu2.alertname (); alert (stu1.alertname= = stu2.alertname);//true shared functions

JavaScript Constructors and prototype objects

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.