Study Notes for getting started with javascript

Source: Internet
Author: User

Variables need to be defined using var in js. undefined variables will be a type of undefine data. Many of you may think of errors as a type of js variables, let's take a look at js variables.


Well, I haven't written any articles for a long time. How long have I come into contact with js? By the way, let's write a js-related article.

Well, thank you for the variable-related stuff today. As long as you are typing code, you have to get in touch with it every day.

Some people say that variables are easy to write? I won't tell you how strange the variables in Javascript are. If you don't learn it well, it will be lost.

Well, take a saved article first. I personally think it is okay to write it.

1. Variable type:Basic and reference types

In js, the basic types are: Number, Boolen, null, String, and Underfined, which are stored in the stack memory. The data length is fixed.
For the reference type, the Object exists in the heap memory, and the Data Length changes (there is also a pointer pointing to this Object in the stack memory ).

2. Reference TypeThe Object can specify any new Member, but it is invalid for the basic type.
 

The Code is as follows: Copy code
Var str = 'ahui ';
Str. name = 'xiaoming'; // invalid.
Alert (str. name); // undefined

3. About Replication
Basic Type: generate a copy in the new stack memory

The Code is as follows: Copy code
Var a = 'astra', B;

B = a; // The B data is copied to the stack memory where a is located.

B = 'strb'; // a = 'stra'


Reference Type: store the same pointer in the new stack memory
That is to say, its value assignment will not open up new memory space. The two variables store identical data.

The Code is as follows: Copy code


Var objA = new Object ();
ObjA. name = 'stra ';
Var objB = objA; // The objB pointer in the stack memory is the same as the objA pointer in the stack memory -- pointing to the same heap Block
ObjB. name = 'strb ';
Alert (objA. name); // strb
Alert (objB. name); // strb


4. PASS Parameters-all parameters in js are transmitted by value, rather than by reference.
(This is equivalent to copying)
Note: passing by value does not mean that the parameters you pass will not be affected by function execution. If the parameter itself is a reference type, the copied parameter itself also contains the same pointer. Changes to the parameter certainly affect the passed variables.

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


Variable Scope

The source is a javaeye post-this is the case in the world. Some people prefer to create problems and some prefer to solve problems. People who make problems bring about employment opportunities to solve problems ......

The Code is as follows: Copy code

<Script type = "text/javascript">
Var a = 100;
Var B = true;
Function test (){
Alert ();
Alert (B );
B = false;
Alert (B );
Var a = 200;
Alert (a/2 );
Alert (++ Math. PI );
Alert (Math. PI ++ );
}
Test ();
</Script>

The first alert is undefined, and the second is true. This problem can also be extended to the question: how can we find external B when alert (B), but alert (a) won't look outside ?!

We all understand that the priority of a local variable is higher than that of a global variable, or that the priority of a variable in the inner scope is higher than that in the periphery. When the JS engine cannot find this variable in the current scope, it will find the peripheral scope. However, before that, there was a serious problem: whether the variable exists in the current scope. An interpreted language like javascript is basically divided into two phases: the compilation phase (which follows the naming conventions of most languages, namely pre-compilation) and the runtime phase. In the pre-compilation phase, it uses a function to divide the scope, and layer by layer opens up the memory space for the variables declared by var (hereinafter referred to as var variables) and function definitions, then perform special processing on the var variable, and assign the initial values to undefined, for example:

We can infer that the current webpage has two functions: a, B, and test. If other things, such as c functions or d variables, are used during runtime, an undefined error will be reported (except when variables and functions are generated using eval or other abnormal means). In addition, they are not assigned a value at most.

Javascript is executed immediately after the space is allocated for the var variable and function definition at runtime, and is executed row by row.

In row 1st, it assigns a value to a of the peripheral scope as 100.
In row 2nd, it assigns true value to B in the peripheral scope.
The test scope of Row 3 is referred to as the inner perimeter scope.
Row 3 immediately calls a of the inner perimeter scope. At this time, it has not had time to assign values! However, it has been declared, so the default value is undefined (in the pre-compilation phase, see the figure), so alert is undefined
When I called B in line 1, The JS engine took the picture I drew and looked at it (SMILE). I found that test has no scope B. I looked out and found B, B is assigned true in the second row, so alert is true.
6th perform a value assignment operation to change the peripheral B Variable to false. Therefore, when the number of rows reaches 7th, alert is false. The following statement is not mentioned.

For comparison, let's rewrite the example below:

The Code is as follows: Copy code
Var a = 100;
Var B = true;
Function test (){
Alert ();
Alert (B );
Var B = false;
Alert (B );
Var a = 200;
Alert (a/2 );
Alert (++ Math. PI );
Alert (Math. PI ++ );
}
Test ();

In this case, B is declared in the scope of the test function.

After understanding the fact that pre-compiled variables are translated into var variables and function definitions are allocated space, many problems can be solved. Let's look at an example in 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 coming!

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 at runtime, a variable of the same name is generated, which is attached to Object. prototype. Which one is closer to the scope of F ?! The test result is var test. So we have:

So we understand that the var variable defined outside the function is not located at the next layer 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 ";

An undefined error is reported because there is no var variable that meets the requirements during the pre-compilation period, and the variable with the same name (2nd rows) has not yet been created during runtime!

What if so ?!

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 many people guessed it was bbb, but it was actually ccc! Some people cannot understand. Isn't the object property priority higher than its prototype property priority ???

This is true, but the object attributes are defined as follows:

The Code is as follows: Copy code

Var o = {test: "eee "}

Object. test = "XXX"

This is defined as a class attribute or a static attribute. The class property priority is lower than the instance property.

Through this figure, we can also learn how inefficient it is to use local variables. In addition, this figure also tells us how advanced a window is (Microsoft loves it most). The Object is inferior to it, let alone the inheritance problem! (In FF and IE)

// The existence of common sense disruption

The Code is as follows: Copy code

Alert (window instanceof Object );
<Script type = "text/javascript"> // the existence of window instanceof Object (alert). </script>

 

To solve this problem, we can see the most difficult one. Class attributes, instance attributes, prototype attributes, and attributes bound very late! However, instance attributes and class attributes are beyond the scope of this article and will not be discussed. These are also not difficult. It is easy to google. google it yourself.

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 ('20140901 ');}
Foo. abc = function () {alert ('20140901 ');}
Var f = new foo ();
F. abc ();
Foo. abc ();
Abc ();

The blue ideal man said the question was wrong. I said, if something is wrong, we can get to the level! Make the correct answer within 10 seconds, indicating that you have learned.

Answer:
<Br/> <br/> <p>

The first one is xyz, f. abc is obviously calling its instance attributes. Generally, the constructor defines the instance methods and attributes as follows: </p> <blockquote> this. XXX = "XXXXXXXX" </blockquote> <p> the second is the foo In the constructor. abc or external foo. abc's problem. We only need to make it clear that the member written outside is bound very late, and the priority is extremely low, so it cannot overwrite the member with the same name internally. </P> <p> Why is the third error reported ?! Because in the pre-compilation phase, the scope of foo () has an abc variable, so abc = function () {alert ('@@@@@')} the window cannot be changed. abc = function () {alert ('@')}, and the following line is more detailed. We call abc, the global variable abc, and the browser will automatically add a window to it. even if abc is not added, the Objcet along the way does not have the abc variable. Therefore, if abc cannot be found outside the scope of f (), an undefined error is reported! </P>

Finally, the JS engine has two opportunities to set variables. During the first pre-compilation period, all var variables are allocated to their respective scopes and the values are undefined. The second time in the runtime, It is variable because it is executed row by row. We can dynamically generate new variables through eval and Function. Their scopes are configurable. Other value assignment statements only fix variables in the top-level scope (window, or just re-assign values. We can also use delete to delete the attributes of an object, forcing it to go out with the same name variable. After the attributes of the referenced object are deleted, the with closure searches for variables with the same name as this attribute on the periphery of the closure.


Let me make a summary. If you operate on basic variables in js, you can do as you want. If it is a reference type, you must think about it, this is the result you want. 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.