The method of JS object creation and the analysis of prototype chain

Source: Internet
Author: User
Tags ming

A. js several ways to create objects

Recently looking at JavaScript advanced programming, where the creation of the object has done a concrete elaboration, you can summarize.

1th mode: Factory mode var sayhello=function() {       return "Hello";  };   function student () {         var  New  Object ();         Child.name= "Xiao Ming";         Child.age= "+";         Child.sayhello=SayHello;        return student;  };     var  x = student ();  alert (x.name);  Alert (X.sayhello ());  

Description

1. Define an object in a function and define various properties of the object, although the property can be a method, but it is recommended to define the property as a method's property outside of the function, which avoids the need to create the method repeatedly

2. When referencing this object, the use of var x = parent () instead of var x = new parent (), because the latter can be a lot of problems (the former is also a factory classic, the latter is called the Hybrid Factory mode), it is not recommended to use the new method of the object

3. Return the object at the end of the function

4. It is not recommended to create objects this way, but you should understand,

2nd mode: constructor mode var sayHello =function() {       return ' Hello ';  };   function student () {                 this. Name = "Xiaoming";           this. Age = "+";          this. SayHello = SayHello;  };     var  x =new  stdent ();  alert (x.name);  Alert (X.sayhello ());  

Description

1. Use the constructor method to create an object in comparison to the Factory mode, without having to re-create the object inside the function, and use this as the reference, and the function does not need to explicitly return

2. As with Factory mode, although the value of a property can be a method, it is still recommended that the method be defined outside of the function

3: Similarly, it is not recommended to create objects this way, but you still need to know

3rd mode: Prototype mode var sayhello=function() {       return "Hello";  };   function student () {           };    Student.prototype.name= "Xiao Ming";    Student.prototype.age= "+";    Student.prototype.sayhello=SayHello;     var  x =New  student ();  alert (x.name);  Alert (X.sayhello ());  

Description

1. Properties are not defined in the function

2. Defining a property with the prototype attribute

3. Similarly, it is not recommended to create objects in such a way

Fourth mode: Mixed constructors, prototype mode (recommended) function student () {    this. name= "Xiao Ming"   ;  this. age=18;       };   Parent.prototype.sayname=function() {       returnthis. name;  };;    ; var  x =New  student ();    Alert (X.sayname ());  

Description: 1. This pattern refers to the mix and match use of the constructor and prototype mode

2. Define all properties that are not methods in the function (constructor mode)

Use prototype of all property values as methods to define outside of a function (prototype mode)

Doing so facilitates the sharing of a function across all instances without repeating the definition, and the function defined in the object's prototype can be called by all instances.

Fifth mode: Dynamic prototyping modefunctionstudent () { This. Name= "Xiaoming";  This. age=18;   ; if(typeofparent.sayname== "Undefined"){         //defined directly within the function body and defined if the function is not definedParent.prototype.sayname=function(){                   return  This. Name; } parent.sayname=true;    }      }; varx =Newstudent ();  Alert (X.sayname ()); 

Description

1. Dynamic prototyping can be understood as a mixed constructor, a special case of prototype mode, just before the instantiation of the object, the conditional judgment

2. In this mode, attributes are defined directly in the function for the properties of the method, but because a conditional judgment statement exists in the function, the method of the property is not created repeatedly when an instance of the object is created

3. It is recommended to use this mode

Two. prototype chain of objects

Once you know how to create an object in JS in several common ways, learn about the inherited problem.

The first thing to be clear : in JavaScript, everything is an object (including functions )

JavaScript sets a prototype for each object that is created, pointing to its prototype object;

(1) For example, when creating an array object

var arr = [1, 2, 3null

(2) Create a function

function foo () {return 0;}

Its prototype chain is: Foo----> Function.prototype----> object.prototype----> Null

When we access the properties of an object, the JavaScript engine looks for the property on the current object, and if it is not found, it is found on its prototype object, if it is not found, has been traced back to the Object.prototype object, and finally, if it has not been found, it can only return undefined.

constructor function

In addition to the direct use of {..} In addition to creating an object, JavaScript can also create objects using a constructor method. The use of it is to define a constructor first:

function Student (name) {    this. Name = name;       This function () {        alert (this. Name + '! ') );    }}

This is not the same as a normal function, but in JavaScript, you can call this function with the key child [new] and return an object:

var New Student (' Xiao Ming'//  ' Xiao Ming '//  Hello, Xiaoming!

Note that if you do not write new, this is a normal function that returns undefined. However, if you write new, it becomes a constructor that binds this to the newly created object and returns the this by default, that is, does not need to write the return this at the last point.

The prototype chain for the newly created Xiaoming is:

Null

In other words, Xiaoming's prototype points to the prototype of the function student. If you create Xiaohong and Xiaojun again, the prototypes of these objects are the same as the xiaoming:

NULL Xiaojun  

The object created with new Student () also obtains a constructor attribute from the prototype, which points to the function Student itself:

// true  //  true//  trueinstanceof// true

The red Arrow is the prototype chain . Note that the object thatStudent.prototype points to is the prototype object of Xiaoming, Xiaohong, and the prototype object has a property constructorof its own, pointing to the Student function itself.

In addition, the function student exactly has a property prototype point to its prototype, but Xiaoming, xiaohong these objects can not prototype this property, but can be used __proto__ This non-standard usage to view.

Now we think Xiaoming, Xiaohong these objects "inherit" from student.

The above is my decision to learn some of the recent JS some of the more good reference and their own experience

Hope to be helpful to everyone

Reference: JavaScript Advanced Programming

Liaoche Blog "JS Tutorial"

The method of JS object creation and the analysis of prototype chain

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.