JavaScript variables, functions, and prototype chains

Source: Internet
Author: User
Tags variable scope

Definition | | Assign value

1-Definition of function
Functions are defined in two ways:
"Defined" functions: function fn () {alert ("Yo, Yo!");}
"Assignment" function: var fn = function () {alert ("Cut to make noise!") "); }
@ When the page loads, the browser scans the JavaScript code and pre-process the defined functions (such as C-like compilation). "Function declaration Promotion"
After processing is performed from top to bottom, the assignment function is only assigned to a variable, not preprocessed, to be processed when it is called.
@ When the function is called in front of the definition, the function of the definition functions normally, and the assignment function will give an error (hint: OFn is not a function).

2-Definition of variables and functions
Variable: ①var A; Define variable A.
②var a = 123; Define variable A and assign a value to variable a.
Function: ①function fn (...)  {...} Declares the function fn.
②var oFn = function (...)  {...} Define the variable ofn and an anonymous function before assigning the anonymous function to the variable ofn.
The @ definition variable and the definition function are preprocessed first, and the variable assignment is done in execution.
@ Defines the function of the variable: only the variable scope is indicated.
Variables that have definitions that are not assigned and values that use undefined variables are undefined.
@ Defines the function: In addition to specifying the function scope and defining the function body structure-including the definition of variables inside the function body and the function, this process is recursive.

            alert (a);    function A () {}            alert (b);    Function B () {}            alert (c);    Undefined            var a = "a";            function A () {}            function B () {}            var b = "B";            var c = "C";            var c = function () {}            alert (a);    A            alert (b);    b            alert (c);    

3-variable assignment
for weakly typed JavaScript, declaring a variable does not need to declare its type.  
with the problem, the use of direct and reference volume is chaotic:
①var x = "111";  var y = x;  x = "222"; alert (y);
in JavaScript, the Y value is 111, that is, the assignment of the string is the direct amount operation, which assigns the data directly to the storage space of Y.
in languages such as Java, the value of Y is 222, which means that X assigns an address (pointer) to the variable y in memory.  
②var x = ["111"];  var y = x;  X[0] = "222"; Alert (y[0]);
in JavaScript, unlike ①, the y[0] value is 222, and the reference amount operation, that is, X assigns the address (pointer) in memory to Y.  
③var x = ["111"];  var y = x;  x = ["222", "333"]; Alert (y[0]);
in JavaScript, the value of Y is again 111, meaning that this assignment is also the Direct amount operation.  
JavaScript parser differences for different types:
var x = "xxxx"; var y = ["11", "22"];
① in a string, the parser directly assigns the string to the variable x (direct amount).
② in the array, the parser assigns the pointer of the array to the variable y (the reference amount).
The above problem ②, x[o] = "222" because there is no new defined value for x , there is no new storage space, only modify the data in its storage space, it is still the reference amount.
in the above problem ③, when creating var x = ["111"], the parser creates a storage space for an array in memory, X obtains the address (pointer) of that space,
then executes x = ["2", "3"] to the new defined value of the array, the parser opens a new The storage space puts this array, and X is a pointer to the new storage space.

From the above, JavaScript variables can store the direct amount can also store the reference amount.
In places such as large string joins and loops, be aware of the effect of this variable characteristic on the efficiency of execution.

var x= ""; var big = "Here is a lump of string ..."; for (i=0; i<100; i++) {     A + = big;} x = A; Because it is a string operation, the use of direct volume, each cycle to manipulate large strings, very cumbersome, inefficient. If you use a reference-volume operation, that is, by using an array, the efficiency will even increase by more than 10 times times: var s = "Here is a big lump of strings ..."; var a = [];for (i=0; i<100; i++) {    

4-Definition and assignment of prototypes
Prototype: If the constructor has a prototype object A, the object instances created by the constructor (object Instance) are copied to the prototype object A.
① Each object has a prototype chain, which itself contains one or more objects, which itself is the starting object.
② in JavaScript, an object or an object instance does not have a prototype, there is no "hold a prototype" argument, there is only "constructs from a prototype" argument.
The constructor has a prototype, and the< constructor >.prototype property points to the prototype.

function fn () {    var name = "Prawn";    var age =;    function code () {        alert ("Spacek!");}    ;} var obj = new fn ();

In the code above:
①obj is an object instance, and Fn is a constructor.
②obj.prototype; Undefined, the object instance has no prototypes.
Fn.prototype; [Object Object], the prototype is an object.
③obj.constructor; Output the function code for FN ().
Fn.construtor; function function () {[Native code]},native code represents the built-in function of the JavaScript engine.
Obj.construtor = = fn; The true,obj is constructed from FN.
④fn.prototype.construtor = = fn; True, the constructor of the function prototype defaults to the function itself.

When the object instance copies the constructor's prototype object, it is replicated by the read-traversal mechanism.
Read traversal mechanism: Refers to the replication of member information to an instance image only when a member of an instance is written.
The property inside the new object that is constructed points to the property in the prototype. When a property of an object instance is read, the property value of the prototype object is obtained.

    Object.prototype.value = "abc";    var obj1 = new Object ();    var obj2 = new Object ();    Obj2.value = ten;        alert (obj1.value);//output ABC, read value    alert (Obj2.value) in prototype object,//output 10, read value in OBJ2 member list    delete obj2.value;//Delete value in Obj2, that is, remove the value from alert (obj2.value) in Obj2 's member list    ;//output ABC, read value in prototype object

The above describes how the read traversal mechanism manages the instance object members list and the object members in the prototype.
① The property's record is added to the list of members of the object only if the property is written for the first time.
② when Obj1 and Obj2 are constructed by new, they are just a reference to the prototype, which avoids the large memory allocations that can be created by creating object instances.
The ③obj2.value property is assigned a value of 10 o'clock, and a value member is added to the member table of OBJ2 and is assigned 10.
This member table records the member names, values, and types that the object sent modified. Follow 2 principles:
A, ensure that the read is first accessed.
B. When the object specifies a property at noon, the entire prototype chain of the object is traversed until the prototype is empty or the property is found.
④delete Obj2.value Deletes the properties of the member table.

Constructor of the prototype
The prototype of the function is an instance of the built-in object () constructor. However, once the object instance is created, the constructor property is always assigned to the current function first.
The root cause is that the constructor property of the constructor (constructor) 's prototype (prototype) points to the constructor itself.

function MyObject () {}alert (MyObject.prototype.constructor = = MyObject);  Displays true, indicating that the constructor of the prototype always points to the delete MyObject.prototype.constructor of the function itself;  Delete the member (the prototype constructor that points to itself) alert (MyObject.prototype.constructor = = Object); alert (MyObject.prototype.constructor = = new Object (). constructor);//The delete operation causes the member to point to the value in the parent class prototype//is displayed as True

In the above example, Myobject.protptype does not differ materially from the new Object (), except that the constructor value of MyObject is assigned to itself when it is created.
There is no clear boundary between the function and the constructor:
When you specify the prototype of a function, the function becomes the constructor.
When you create an instance with new, the engine constructs a new object, connecting the prototype chain of the new object to the function prototype property.

"Prototype replication" in prototype inheritance
You can point to the same constructor by setting the constructor property of the instance created by the different constructors.

function MyObject () {}function Myobjectex () {}myobjectex.prototype = new MyObject (); var obj1 = new MyObject (); var obj2 = n EW Myobjectex (); alert (Obj2.constructor = = MyObject);    Truealert (MyObjectEx.prototype.constructor = = MyObject);    True

Obj1 and Obj2 are instances produced by different two constructors (MyObject and Myobjectex). However, two alert outputs true, which is the instance generated by two different constructors whose constructor attribute points to the same constructor. This embodies "prototype replication" in prototype inheritance. The prototype of Myobjectex is an object instance constructed by MyObject, that is, Obj1 and Obj2 are objects copied from the MyObject prototype, so their constructor points to myobject!

JavaScript variables, functions, and prototype chains

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.