In-depth study of JS constructors and prototypes

Source: Internet
Author: User
Tags hasownproperty

Soon to leave from Sina, the mood is more relaxed recently, take a little space to tidy up the mechanism of the structure function and prototype.

We all know that in the classic design mode we are most commonly used in the Factory mode, the constructor mode, the prototype model of these kinds of, it sounds like ' mode ' seems to be very tall on the appearance, in fact, we in the daily writing JS code will often use.

Simply put, the factory pattern is a function that we usually write, and when we want to complete a function, we call this function over and over. Such as:

function Add (b) {    return a +b;}

This is a very simple code, the completion of a very simple two-number addition of the function, when we need to add two number of calculations, call this function can be.

I want to make it clear here: The Factory mode is not necessarily lower than the constructor mode, because it is not the same situation. Foxconn is the world's largest foundry factory, but we can't say it's low, and its factory-running model is also very advanced.

However, the Factory mode can not realize the problem of instance recognition (too obscure, not understand), simply can not realize the Java, C # and other classes of functions. Of course, JS has no class, just a constructor to simulate the class. It is easier to create a class and then invoke the class with the same or similar function to produce different instances.

Under what circumstances can a general function be used, and when is it better to use a class (constructor)? I don't think this is conclusive. When implementing a very simple function, such as the add-on function above, there is no need to become a constructor pattern. However, when we want to encapsulate a large module, such as mobile phone scrolling diagram and other more complex functions, with the constructor is relatively better, because the package into a class, can maintain a good encapsulation, more in line with the object-oriented characteristics.

This is not the design pattern in the small talk, pull back to the point.

Constructors we all know how to construct, so what happens behind the time when new is an instance? First look at a constructor function

function Person (Name,age,gender) {    this. name=name;      this. Age = Age ;     this. gender=gender;
This.work = function () {
alert (this.name);
}} var New Person (' zhangsan ', ' Male ');

So what is this example of Person1? Function? Object?

If Console.log (Person1) can be seen clearly, is an object {' name ': ' Zhangsan ', Age:24,gender: ' Male ', work:function () {alert (this.name)} };

If you create another person2, then the attribute values in the Person2 and the values in the Person1 are completely independent, so is it possible for us to proceed further with the instance object?

However, this definition is debatable, because each time an instance is created, the constructor executes once, so each instance has the same work function definition. This consumes both memory and no need. So we need to transform this constructor into the following:

function Person (Name,age,gender) {    this. name=name;      this. Age = Age ;     this. gender=gender;     this. Work = Work;} function Work () {    alert (this. name);} var New Person (' zhangsan ', ' Male ');

Do you think this is a lot better?

However, this is not optimal, because the work function is in the global, but it is used only for the constructor of the person, so the disadvantage is 1, exposed to the global 2, no encapsulation

The prototype of the function can then be used. Notice two concepts: The function is inherently prototype, but the normal object does not. The normal object has a proto_ _ property, so the instance object can access the prototype property of the function through the __proto__ property. This is a link to the prototype chain. After the prototype chain.

The use of prototype can be a good solution to the above two shortcomings of the constructor function. As follows

function Person (Name,age,gender) {    this. name=name;      this. Age = Age ;     this. gender=gender;   } Person.prototype={work    :function() {        alert (this . name);}    } var New Person (' zhangsan ', ' Male ');

You see, is this more optimization, more object-oriented thinking?

The origins and benefits of the prototype are over, and the prototype chain mentioned above is said again.

The __prototype__ property of the instance Person1 can access the prototype property of the person, so the work function can be parsed correctly. This is the prototype chain. Specifically, it is:

Person1 to look for attributes, first see if you have this attribute. (Do not forget that Person1 is an object), if not, well, then go to the person's protype to find. Found, and then executed on it.

Here is the order to look for: self-----"the prototype of the constructor---" Object prototype, if not, then the error.

So what if we want to determine if one of the properties of an instance is on a class (constructor) or a prototype of a class? Here there is an in operation that conforms to the hasOwnProperty method to locate.

Why should we judge it? Because some of the requirements may be as long as the instance resides on a property on the class, do not prototype the properties. Then these two operators/methods will be of great useful.

functionPerson (Name,age,gender) { This. name=name;  This. Age =Age ;  This. gender=gender; }person.prototype={work:function() {alert ( This. Name); }}varPerson1 =NewPerson (' zhangsan ', ' Male '); Console.log (Person1.hasownproperty (' name '));//trueConsole.log (' name 'inchPerson1);//true

If hasOwnProperty returns True, then the Name property is on the class. The In operator returns TRUE, indicating that the name attribute is definitely on the class or on the prototype of the class.

The hasOwnProperty and in can be positioned to determine.

I have encountered a face test that examines the constructors and prototypes, presumably:

functionPerson (Name,age,gender) { This. name=name;  This. Age =Age ;  This. gender=gender; }person.prototype={work:function() {alert ( This. Name); }}varPerson1 =NewPerson (' Lisi ', ' male '); Person.study= ' 中文版 '; Person.prototype.course= ' Math '; Console.log (person1.study); Console.log (person1.course);

OK, look at Console.log (person1.study); What's the return? Look again at Console.log (Person1.course), what is the return?

Oh ~ Oh ~

The answer is undefined and math.

Why is that? This involves the dynamic nature of the prototype. What do you mean? This means that the properties on the prototype are dynamic, and although the instance is created earlier, prototype is automatically updated when the properties on the prototype are created below.

But the constructor is not dynamic, and defining the person class to add properties or methods to the person class later does not add a success.

To get to the bottom, the constructor and prototype this is really water is very deep, a lot of pits, we need to seriously study, do not adhere to the effect out of everything.

Let's write it down here!

In-depth study of JS constructors and prototypes

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.