JS prototype scope

Source: Internet
Author: User

Before you know the JavaScript prototype chain, you must first know what a prototype is.

In JavaScript, a prototype is an object that can be inherited by a prototype. Since the prototype is an object, can any object be called a prototype? Yes, remember it. What objects have prototypes? Any object (Undefined,null,boolean,number,string is the primary type, not an object) has a prototype by default, but the prototype is also an object, so the prototype of the object has a prototype, remember, the following is useful.

JS in the object contains a pointer to the prototype object, but it is not directly accessible, in order to easily see the prototype, Chrome and Firefox provide the __proto__ property, but this is only provided by the browser, a different browser may not provide this property, The ECMA introduces the standard prototype accessor Object.getprototype (object).
Here again the ECMA explains the difference with JavaScript. ECMAScript is a standard, and JavaScript can be understood as a collection in which each browser implements its own JavaScript based on this standard (different browsers may not perform the same piece of code), JavaScript is actually made up of three different parts: the core (ECMAScript), the Document Object Model (DOM), the browser object model (BOM). No more withdrawals.

View a prototype of an object, enter it on the browser console

function Human (name) {    this. Name = name;           This function () {        Console.log (this. name);}    ;} var New Human ("Fzk");
H

You will see the __proto__ property, and you can see that H has a prototype attribute, which has a constructor property, which says that the prototype is also an object, so there is also a __proto__ prototype object. constructor is a function type object, which is a function when an object is instantiated. What is the process of object instantiation (new)? Actually, it's four things I did.

New Human ("fzk") = {  var obj = {};  obj.__proto__ = Human.prototype;  var result = Human.call (obj, "Fzk");  Return typeof result = = = ' obj '? Result:obj;}

(1) Create an empty object obj;
(2) The __proto__ of obj points to the Human prototype object prototype, and the prototype chain of the Obj object is established: Obj->human.prototype->object.prototype->null
(3) Call the human function in the execution environment of the Obj object and pass the parameter "FZK". Equivalent to var result = obj. Human ("Fzk"). When this sentence is executed, obj generates the property name and assigns the value "Fzk".
(4) Examine the return value returned by step 3rd, return the obj as a new object if there is no return value or return a non-object value, or return the return value as a new object.

In the process of re-creation, the constructor is pointed to the constructor of the prototype.

Knowing the process above, the following code is well understood.

h.__proto__ = = = Human.prototype
human.prototype.__proto__ = = = Object.prototype
Person.prototype.constructor = = Person

Here again see prototype, here explain prototype and __proto__
1. All objects have a __proto__ property
2. For function objects (functions, defined by the function () {}), there is an additional prototype attribute.

In JavaScript, everything is object. A function object is also an object, and it has a prototype. What is the scope chain of the human (function object) here?

Can be seen: Human->function.prototype->object.prototype->null

Ultimately, it will point to object. The above mentioned function object will have the prototype property, why here (more than here, the above also used) object also has the prototype property.

typeof Object> "function"

On the console, tapping on the code above, you will find that object is a function.

Finally look at:

Explain so much, and finally look at the official definition: ECMAScript describes the concept of the prototype chain, and the prototype chain as the main way to implement inheritance. The basic idea is to use a prototype to let one reference type inherit the properties and methods of another reference type. Briefly review the relationship of constructors, prototypes, and instances: each constructor has a prototype object, and the prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. So what happens if we let the prototype object be equal to another instance of the type? Obviously, the prototype object at this point will contain a pointer to another prototype, and a pointer to another constructor is also included in the other prototype. If another prototype is another type of example, then the relationship is still established, so that the level of progression, constitutes an example and prototype chain. This is the basic concept of the so-called prototype chain.
Is it super-confused at first? Is it a question of life? But through the example of careful understanding, sure enough, ECMAScript said is concise. JavaScript is also the use of the prototype chain to achieve inheritance.
We understand the prototype, definitely want to use it better, under what circumstances will use the prototype? We first need to know what the prototypes are,
1. According to the official definition, it must be used to achieve inheritance. But basically we don't have to do it ourselves, unless you want to manually modify the object's prototype pointer.
2. The attributes defined in the prototype can be shared by all instances (why?). Because the prototype of the function object is assigned to the __proto__ of the instance object when instantiated, the object will find the property based on the prototype chain and the properties defined in the prototype property of the function object will be found by the instance through the prototype chain, but note that This can be found because the prototype chain lookup instead of the instance object has this property, is it not possible to think of multiple instanced objects can share a memory space, the fact is true. In this case, you are thinking carefully about whether new is actually equivalent to the instance object inherits the properties and methods of the original function object, and the meaning of instantiation in JavaScript is actually inherited. It's going to be a lot more than that, so you can reduce memory usage. You can also add methods dynamically.

The above two points of analysis also know the use of the prototype, 1. Inheritance, 2. Multiple instance objects share a piece of memory, 3. Dynamically add methods to all instances.

Continue to remove the meaning of new in JavaScript, which is said in parentheses. JavaScript says all things are objects, why create objects through new, Lily? In a closer look, JavaScript says that a instanceof b = = = True, so A is an example of B, and how does this instanceof judge? Just like this:

var L = a.__proto__; var r =if(L = = = R)returntrue;

Is not feeling good coincidence, is so coincidence, in the instantiation of H, is the human prototype to H __proto__. H also inherits the properties of the original function object, so new is intended to have the properties and methods of the original object. Don't understand? is to let {}.__proto__ = Human.prototype, at this time {} is an object and is also an instance of Human, but now {} What property does not have. The object H through new has the properties and methods of human, and H is also an instance of human. So, the meaning of the new existence of JavaScript is not to wear an object, but to implement JavaScript inheritance.

Prototype chain understanding of the almost, look at the following output is all-round understanding

functionAnimal (name) { This. Name =name; } Animal.color= "BLACK"; Animal.prototype.say=function() {Console.log ("I ' m" + This. Name);  }; varCat =NewAnimal ("Cat"); Console.log (Cat.name,//CatCat.height//undefined  ); Cat.say (); //I ' m catConsole.log (Animal.name,//AnimalAnimal.color// Back  ); Animal.say (); //Animal.say is not a function

After reading the prototype chain, look at the scope chain.
The scope of JavaScript is a non-block-level scope and is a function-level scope. What do you mean? In other words, if, for, and while .... The following braces do not isolate scopes, and the attributes defined in these curly braces are a property of a property defined outside the curly braces. Take a look at the classic example

var data = [];  for (var i = 0; i < 3; i++) {    data[i]=function() {        console.log (i);    }
//data[0] (); three times respectively print 0, 1, 2}data[0] (); // 3data[1] (); // 3data[2] (); // 3

Understanding the non-block scope, this is very well understood. Here, I is equivalent to the global scope of the variable, the data array is pointing to the function pointer to print I, function is to print I, after the end of the loop, I has become 3, when printing I of course printed out is 3.
This leads to the concept of a global scope, which corresponds to a local scope. A global scope is where an object can be accessed anywhere in the code, a variable with the outermost definition, a variable without a var modifier, and a Window object's properties are global scope variables. A variable defined in a local scope is used only within the function.

When it comes to scopes, you must say closures. What is a closure, the so-called "closure", refers to an expression (usually a function) that has many variables and environments that bind them, and therefore these variables are also part of the expression. My understanding is that a function can use a property defined in another function, and these properties will be closed.

function count () {    var x = 0;         return {        functionreturn + +x;}        ,functionreturn -- x;}}    ;}
c = count ();
C.increase ();

Closures and the scope chain are related. Each execution environment has a VO that holds information such as variable function parameters and continues to look up when a variable is not found from the current execution environment. This creates a chain of scopes, and the properties of the closure are those that are not found in the current environment and are found in a certain layer of the superior, but this variable is not a global scope variable. Normal non-closure functions after the function is executed, all property variables are destroyed, but the variables in the closure are not destroyed after the function is executed. Therefore, the closure of the need to pay attention to the problem of memory leaks.

Scenarios for closure applications:
1, the security of the variables within the protection function. X can only be accessed through count (), in addition, there is no way to access it.
2, save the data. This app is a lot of places, counters, data collection ...

Why write such a big cheat article, is to say the last thing, JavaScript in the case of both inheritance and closure of the situation when looking for a variable is how to find. First, through the scope chain, find out which object this property belongs to, and then look up through the scope chain.

Reference:

Http://www.jb51.net/article/78709.htm

Http://www.cnblogs.com/wilber2013/p/4909459.html

Http://www.cnblogs.com/wilber2013/p/4924309.html

JS prototype scope

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.