Learning notes for the JavaScript Primer tutorial

Source: Internet
Author: User
Tags closure constructor eval function definition what inheritance


Oh, for a long time did not write articles, the recent contact with JS compare how long by the way to write a JS-related article.

Well, thank you today for variables related to it, variable this thing as long as you are knocking on the code every day have to contact it.

Some people say that variables are good to write? I'm not going to tell you that the variables in JavaScript are strange, and it's really going to get dizzy if you don't learn them well.

OK, first take an existing text, personal feeling write is also OK.

1. Variable type: basic type and reference type

In JS, the basic type: number,boolen,null,string,underfined stored in the stack memory, the data length is fixed.
The reference type, object exists in heap memory, and the length of the data is variable (at the same time there is a pointer in the stack memory pointing to the object).

2. A reference type object can optionally specify a new member, but is not valid for the base type.

The code is as follows Copy Code
var str= ' Ahui ';
Str.name= ' xiaoming ';//invalid.
alert (str.name);//undefined

3. With regard to replication
base type: Generate a copy in the new stack memory

The code is as follows Copy Code
var a= ' stra ', B;

b=a;//Here Club B data is copied to the stack memory where a resides

b= ' strb ';//a= ' Stra '


Reference type: Save an identical pointer in the new stack memory
That is, its assignment does not open up new memory space. Two variables save exactly the same data.

  code is as follows copy code


& nbsp;       var obja=new Object ();
        obja.name= ' stra ';
        var objb=obja;//objb pointers in stack memory and obja pointers in stack memory are the same values-point to the same heap block
         objb.name= ' STRB ';
        alert (obja.name);//STRB
         Alert (objb.name);//STRB


4. All parameters in the pass parameter--js are transmitted by value, not by reference.
(This is equivalent to copying)
Note: Passing by value does not mean that the parameters you pass are not affected by the execution of the function. If the parameter itself is a reference type, then the copied parameter itself contains the same pointer, and the change of the parameter will of course affect the variable being passed.

The code is as follows Copy Code


var o=new Object;
O.name= ' Ahui ';
function func (obj) {
Obj.name= ' This variable is changed ';
}
Func (o);
alert (o.name);//this Varibale is changed


Scope of variables

The source for the javaeye of a paste-this world is the case, some people like to create problems, people like to solve problems. Create problems for people who solve problems to bring job opportunities ...

The code is as follows Copy Code

<script type= "Text/javascript" >
var a=100;
var b=true;
function Test () {
alert (a);
alert (b);
B=false;
alert (b);
var a=200;
alert (A/2);
alert (++MATH.PI);
alert (math.pi++);
}
Test ();
</script>

What first alert is undefined, and the second is true. This problem can also be extended to--alert (b) How to find the external B, and alert (a) will not look outside?!

We all know that a local variable has precedence over a global variable, or that an inner-scope variable has a higher precedence than the outer edge. When the JS engine cannot find this variable in the current scope, it is looking for the perimeter scope. Before that, however, there is a serious question of whether this variable exists in the current scope. An interpreted language such as JavaScript is basically divided into two stages, the compile period (the following is the salutation of most languages, called precompilation) and the runtime. In the precompiled phase, it uses a function to divide the scope, and then layer for its VAR declared variables (hereinafter called VAR variable) and function definition to open up memory space, and then special treatment of VAR variables, all assigned the initial value of undefined, the following figure:

We can infer that the current Web page has two A, a B, a test function. If you use other things in the runtime, such as the C function or the D variable, you will report undefined errors (except for those that generate variables and functions in abnormal ways, such as Eval), and they have a maximum of unassigned warnings.

The runtime of JavaScript is executed immediately after assigning space to the var variable and the function definition, and is executed line-by-row.

Line 1th It assigns a value of 100 to the perimeter scope
Line 2nd It assigns a value of true for the perimeter scope
The 3rd row is the scope of test, which we simply refer to as an inner-enclosing scope.
Line 4th immediately calls the inner scope of a, then it has not yet time to assign the value of it! However, it has been declared, so the default value is undefined (in the precompiled phase, see figure), so alert is undefined
The 5th line on the call to B, the JS engine took my picture to see (laugh), found that the scope of the test is not B, eyes looking out, found B, and B in the second row of the assignment is true, so alert is true.
The 6th behavior is an assignment operation that assigns the peripheral B variable to false. Alert is false to the 7th row. The following statements are not mentioned.

As a contrast, let's rewrite the example:

The code is as follows Copy Code
var a=100;
var b=true;
function Test () {
alert (a);
alert (b);
var B=false;
alert (b);
var a=200;
alert (A/2);
alert (++MATH.PI);
alert (math.pi++);
}
Test ();

B is also declared within the scope of the test function.

After mastering the fact that precompilation is the allocation space for var variables and function definitions, many problems are solved. Let's look at an example from the Rhino book.

The code is as follows Copy Code
var scope = "global";
function f () {
alert (scope);
var scope = "local";
alert (scope);
}
f ();

The answer is ready!

Let's look at more complex examples.

The code is as follows Copy Code
Object.prototype.test = ' wrong ';
var test = ' right ';
(function f () {
alert (test);
})();

The difficulty of this problem is that, when the runtime, it generates a variable of the same name, it is attached to the Object.prototype, exactly which distance f () the scope of a little bit closer?! The test result is var test. So we have the following figure:

So we understand that the VAR variable originally defined outside the function is not located at the next level of the window scope.

We continue to deepen the difficulty.

The code is as follows Copy Code
(function f () {
alert (test);
})();
Object.prototype.test = ' CCC ';
Object.test = "BBB"
Window.test = "AAA";

The report did not define an error because the pre-compilation period did not meet the required var variable, and at runtime, the variable with the same name was not established at the time of the call (line 2nd)!

What if it does?!

The code is as follows Copy Code

Object.test = "BBB";
Object.prototype.test = ' CCC ';
Window.test = "AAA";
(function f () {
alert (test);
})();

It is estimated that a lot of people guess is BBB, in fact, is ccc! some people are puzzled, not the object's attribute priority than its prototype attributes higher priority???

No, that's true, but the object's properties are defined in this way:

The code is as follows Copy Code

var o = {test: "eee"}

Object.test = "XXX"

This is defined as a class attribute, or a static property. Class attribute precedence is lower than instance property

Through this chart also educates us, must use the local variable ah, otherwise, one layer climbs up, the efficiency is how low. In addition, this picture also tells us how the window is a high level of existence (Microsoft Favorite), object is lower than it, let alone what inheritance problem! (in FF and IE)

Subvert the existence of common sense

The code is as follows Copy Code

Alert (window instanceof Object);
<script type= "Text/javascript" >//Subversion of common sense presence alert (window instanceof Object); </script>

We'll see the hardest part of this. Class properties, instance properties, prototype properties, very late bound properties all got it! However, the instance properties and class properties are beyond the scope of this article and are not discussed. These are not too difficult, it is easy to Google to the Google bar.

The code is as follows Copy Code
function foo () {
FOO.ABC = function () {alert (' Def ')}
THIS.ABC = function () {alert (' xyz ')}
ABC = function () {alert (')};
var abc = function () {alert (' $$$$$$ ')}
}
FOO.PROTOTYPE.ABC = function () {alert (' 456 ');}
FOO.ABC = function () {alert (' 123 ');}
var f = new Foo ();
F.ABC ();
FOO.ABC ();
ABC ();

The blue ideal person says this problem is not good, is wrong. I said, wrong is good, so as to test the level! 10 seconds to make the right answer, that means learned.

Answer:
<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <b R/> <br/> <br/> <br/> <br/> <p>

The first for XYZ,F.ABC is obviously called its instance property, which is usually the constructor that defines the:</p> <blockquote>this.xxx of instance methods and Instance properties = "XXXXXXXX" </blockquote > <p> The second one is the problem of FOO.ABC or external foo.abc within the constructor. We just need to figure it out. The one that was written on the outside is very late. Bound members, extremely low priority, cannot overwrite the internal name of the same person. </p> <p> Why does the third one complain?! Because the scope of Foo () has an ABC variable in the precompilation phase, ABC = function () {alert (')} will not change window.abc = function () {alert (')}, And the following line is no more to mention. And we call ABC, global variable ABC, the browser will automatically add WINDOW.ABC to it, even if not added, along the objcet there is no ABC of this variable, so it is in the role of F () can not find ABC, on the report undefined error! </p>

Finally, the JS engine has two chance to set the variable. For the first time in the precompiled period, all VAR variables are assigned to their respective scopes, and the values are undefined. The second time at run time is variable because it is executed on a line-by-row basis. We can dynamically generate new variables through eval and function, and their scopes are configurable, and other assignment statements simply fix the variables in the top-level scope (window) or simply reassign them. We can also use Delete to delete an object's properties and force it to go outside with the same name variable. The with closure looks for a variable with the same name as this property at the perimeter of the closure after the properties of its referenced object are deleted


Let me make a summary, JS if the operation is the basic variable then you can do as you want, if it is a reference type, then you must think carefully, this is not the result you want to remember!!!

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.