What is the scope chain, what is the prototype chain, what are the differences between them, and what exactly do they refer to in JS?

Source: Internet
Author: User

Scope is for variables, for example, we create a function that contains a function, and now there are three scopes

Global scope ==> function 1 Scope ==> function 2 scope

The scope is characterized by first finding it in its own variable range, and if not, it will look up along the scope.

Such as:

var a = 1;function B () {    var a = 2;    Function C () {        var a = 3;        Console.log (a);    }    C ();} b ();

The last print is 3, because when the function C () is executed, it finds the variable a in its own scope, so it will not continue to look up, if it is not found in function C () will continue to look up, always find the global variable A, this lookup process is called the scope chain.

I wonder if you have any doubts about why function C can look up variable A in function B, because function c is created in function B, that is, the scope of function C includes the scope of function B, and of course the global scope, but function B cannot find the variable in function C because the scope will only look up.

So what is a prototype chain?

The prototype chain is for constructors, for example, if I create a function and then use a variable to new The function, then the new function inherits the property of the created function, and then if I access a property of this function from new, But I did not define this variable in the new function, and then it looked up (to the function that created it), and the process of finding it was called the prototype chain.

Object ==> Constructor 1 ==> Constructor 2

As with inheritance in CSS, the style of the parent element is inherited if it is not defined by itself.

function A () {};a.prototype.name = "chasing the Dream"; var B = new A (); Console.log (b.name); Chasing the dream son

What is the scope chain, what is the prototype chain, what are the differences between them, and what exactly do they refer to in JS?

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.