JavaScript Basic Practice (1)--a 10-side ambush test of the prototype chain surface

Source: Internet
Author: User
Tags class definition

In front of the foundation, all skills are floating clouds.

The title is like this.

Requires the output of the console to be written out.

function Parent() {            this.a = 1;            this.b = [1, 2, this.a];            this.c = { demo: 5 };            this.show = function () {                console.log(this.a , this.b , this.c.demo );            }        }function Child() {    this.a = 2;    this.change = function () {        this.b.push(this.a);        this.a = this.b.length;        this.c.demo = this.a++;    }}        Child.prototype = new Parent();         var parent = new Parent();        var child1 = new Child();        var child2 = new Child();        child1.a = 11;        child2.a = 12;        parent.show();        child1.show();        child2.show();        child1.change();        child2.change();        parent.show();        child1.show();        child2.show();
Knowledge points involved in the topic
    • The point of this
    • Prototype prototype chain
    • Inheritance of Classes
    • Differences between primitive types and reference types
      Each knowledge point can be taken out to do a separate thematic study.
Knowledge points required for problem solving
    • 1. Constructors have a prototype property that points to the prototype object of the constructor, and the instance shares the same prototype object;
    • 2. When the instance is generated, a new heap memory is generated in memory, and the general operation of the instance will not affect the other instances because it occupies different space in the heap memory and does not affect each other.
    • 3. Each instance has an implicit prototype __proto__ that points to the constructor's prototype object;
    • 4. this the direction of the problem, the common situation contains the following several:
      • 4.1 as an object method, the person who calls is to whom (the main concern of this article)
      • 4.2 As a function call, point to the global top-level variablewindow
      • 4.3 When called as a constructor, new when an operator generates an instance, this in the constructor points to the instance
      • 4.4 call and apply methods, displays the specified this binding as the specified context
    • 5. The literal way ( also has the data to translate literal to direct volume , the individual thinks the latter kind of translation is actually more intuitive and the image) carries on the object and the group assignment (the array essence is also the object), is the reference, namely in the heap memory generation resources, The variable is generated in the stack memory, and then the variable points to the address of the resource.
    • 6. The lookup rules of the prototype chain follow the shortest path principle, which is to find the instance properties first, then go through the prototype chain to find the specified attribute, until the end of the prototype chain Object.prototype null , and if the instance itself and the entire prototype chain do not exist, the found property is returnedundefined
    • 7. Assignment statements differ in detail when assigning values to original values and reference types.
Start Section 1.parent.show ()

There is basically nothing to explain.
The answer 1 [1,2,1] 5 can be obtained by directly taking the value;

2.child1.show ()

ChildThe constructor of the method is originally pointing Child to the

The topic explicitly points the Child prototype object of a class to Parent an instance of the class, which is one of the common inheritance methods in JavaScript object-oriented programming. Instead of Child.prototype Parent pointing to parent Parent This class, you need to be aware of the instances that point to

The output answer is available directly in the console operation.11 [1,2,1] 5

What's confusing here is that the last column of the array that this.b points to is why 1 not 11 ?

Let's take a look at Child1:

When child1.show() This method is executed, as child1 an Child instance, it is a property of a , so show() the method this.a will directly point to the value of this property, 11 that is, not continue along the prototype chain to the The __proto__ a attribute on the object being referred to;

Then look for this.b , because child1 there is no B this property, so along the prototype chain to the parent top of the B property, its value is an array, the first 2 is a constant nothing to say, the last item of the array is a reference, The pointer here is not a dynamic point, because at new Parent() this point it has been executed once, to determine the parent.a resource pointed to, that is, the child1.__proto__ a attribute in the resource pointed to, that is, the value 1.

Extended Thinking

It is important to note that:

1. From the code point of view, the child1.__proto__.b third item of the array is pointed child1.__proto__.a to, then we change the value at this point child1.__proto__.a , whether it will affect child1.show() the result:

The answer is that wood has an effect, why does it seem that a property that points to the same address has a different value? Because the parent instance is generated, it this.a points to an original value of 2, so this.b the third item in fact is assigned a primitive value, so at first glance it looks like the assignment of a reference type, but it is not. The original value assignment opens up new storage space, making this.a this.b[2] the values equal to each other, but pointing to different addresses in the heap memory. more detailed explanations can be found in the blog posts recommended in "Extended reading" .

2. How do child1.__proto__.b you make the third item of the array output 11 ?

    • Modify after instantiation
      Because in the Parent class definition, the third item of theB property Array is a pointer to the value of the a property, which means that Parent the reference is dynamically pointed before instantiation, so as long as the Parent class definition is changed before instantiation this.avalue, you can achieve the desired effect, and if it is Parent already instantiated, you will only be able to explicitly modify the *.b[2] value of this property.
    • Get/set Method Synchronization
      Another way to do this is by setting the method for the a property, which get/set synchronously modifies the value whenever the value of the a property changes, b[2] and the result of the code and run is as follows:

3.child2.show ()

If you understand the above explanation, here's the same answer:12 [1,2,1] 5

Then the code executes: Child1.change (); Child2.change ();

4.parent.show ()

parentis an Parent instance of a class that points to another instance of the Child.prorotype Parent class, which is two resources in the heap memory and does not affect each other, so the above operation does not affect the parent instance.
The output remains the same: 1 [1,2,1] 5 ;

5.child1.show (), Child2.show ()

child1change()what happened after the method was executed?

This.b.push (THIS.A)
Due to the dynamic pointing property of this, this.b will point to the Child.prototype B Array, THIS.A will point to child1 the a property, so Child.prototype.b it becomes [1,2,1,11];

THIS.A = This.b.length
The point in this this.a statement this.b is consistent with the previous sentence, so the result is child1.a 4;

This.c.demo = this.a++
Because the child1 property does not have a C attribute, so here this.c will point to a value of Child.prototype.c this.a 4, the original type, so the assignment is directly assigned to the value, Child.prototype.c.demo the result is 4, and This this.a is then increased from 5 (4 + 1 = 5).

Then, the child2 methods are executed, change() child2 and child1 both are Child instances of the class, so their prototype chain points to the same prototype object, which is the Child.prototype same parent instance, so child2.change() All of the statements affecting the prototype object will affect child1 the final output result

This.b.push (THIS.A)
Because of this dynamic pointing attribute, this.b will point to the Child.prototype B Array, THIS.A will point to child2 the a property, so Child.prototype.b it becomes [1,2,1,11,12] ;

THIS.A = This.b.length
The point in this this.a statement this.b is consistent with the previous sentence, so the result is child2.a 5;

This.c.demo = this.a++
Because the property child2 does not have a C attribute, it this.c will point here, so the Child.prototype.c execution result is a value Child.prototype.c.demo child2.a of 5, and the child2.a final self-increment is 6 (5 + 1 = 6).

The output command is then executed, and the final result is output:
Child1.show (): 5 [1,2,1,11,12] 5
Child2.show (): 6 [1,2,1,11,12] 5

    • Extended Thinking
      Oneself in the problem, in this.c.demo = this.a++ error, I thought here will be quoted, but the actual value is passed, the analysis after understanding because this.a the point is a primitive value, so the equivalent of the original value is assigned to the object properties , so child.c.demo the value after the assignment will not be child.athe impact of the change. If child.a It is a reference type, what will the result look like?
      We make some changes to the source code that will child.a point to an object (that is, the reference type):

      After running, you will see that the value changes as the value Child.prototype.c child1.a child1.a is a reference type, and the assignment process causes Child.prototype.c and child1.a points to the memory space address of the same resource. For a more detailed explanation of the original type and reference type , you can refer to the blog at the end of the article extension reading.
Harvest and Reflection

1. The basic knowledge is the scattered details, must be based on the mentality of death to study.

2. The basic knowledge is the most boring, but also really open the gap between people and things, but also you want to enter the big manufacturers must cross the threshold, important but not urgent . The same is rookie, some people 3-5 years later became the front-end architect, some people 3-5 years later in the endless new framework to the button binding event, want to become what kind of person, will pay what kind of effort, most of the time is no fault. The basics are important! It's important! It's important!

3. The basis of this thing is to keep looking, like 红宝书(javascript高级程序设计) and 犀牛书(javascript权威指南) this book, preferably more than a few times, some difficult to understand the phenomenon is often due to the underlying principle of understanding is not in place, bought new book directly used to monitor you do not feel distressed? Himalaya There is a free accompany you reading series, 30 informal audio throughout the Red Book content, to do not like to read the children's shoes is absolutely a great boon.

Extended Reading
    • JavaScript data manipulation-the nature of primitive and reference values
    • [JavaScript Advanced Programming] Chapter 4th

JavaScript Basic Practice (1)--a 10-side ambush test of the prototype chain surface

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.