"JavaScript from getting started to giving up" JS Basics-01

Source: Internet
Author: User
Tags cos variable scope

As a front-end developer, JS is the guy we walk around to eat. Basically a front-end personnel can value how many oceans, see JS. Although various frameworks abound, but in the final analysis of native JS is the hard truth.

Learning any new things actually follow the 10,000-hour talent law, as long as the time, there will be a harvest. The difference between man and man is only how much it is harvested. On the question of talent, we do admit that some people are actually more powerful than others in some areas. But most of us are ordinary people, do not need talent, only need to through the simple accumulation of time can be mixed mouth food.

The piano can reach the level of the people are a few, most of the art students are ordinary, graduated from a piano teacher when, run a training school to make money to marry a daughter-in-law children, most write a book or something. It is only when you invest enough time that you find that some people are really better than you, and that this is a good time to discuss talent issues. Therefore, do not self-denial, is the real growth of the beginning.

Let's get down to it.

  One, the composition of JavaScript

JavaScript consists mainly of the following 3 parts:

ECMAScript: Interpreter, interpreter

Dom:document object Model (Document object models)

Bom:browser Object Model

ECMAScript is analogous to the role of translation, translating well-written, readable code into binary code that can be recognized by computers, and translating the information back to us with computer feedback. ECMAScript is the core of JS, often called: interpreter.

ECMAScript provides the most basic function for JS, but these functions are very limited, how can JS have the ability to write Web page code? Now we're going to use DOM. The document in the DOM is actually an HTML document, and the DOM also gives JS the ability to manipulate HTML. In JS, the DOM is presented in document form.

BOM makes JS has the ability to operate the browser, in JavaScript, the BOM in the form of window, with the BOM,JS has a similar pop-up window, close windows, copy content to the Clipboard and other browser-related functions.

From a compatibility point of view, ES (ECMAScript) basically does not have compatibility issues, DOM has some operational incompatibility, and the BOM is completely incompatible, so as far as possible to avoid the use of the BOM, this can save a lot of trouble.

  Two, variable type

The first thing to say about variables, literally understood, is the amount of change that can be placed in a programming language, which is the amount of change that can be assigned. and variables corresponding to the constant, we often encounter such as, 10,20 such a number can not be changed, is a constant, a definite value. cannot be assigned and cannot be changed.

In JS we divide the variables into multiple types.

var a = 1024; Alert (typeof a); var a = ' cos '; Alert (typeof a); var a = true; Alert (typeof a); var a = function () {   alert (' cos ');} alert (typeof a); var a = document; alert (typeof a);

TypeOf is a unary operation that can be any type before it is placed in an operand. The return value is a string that describes the type of the operand.

We can return the variable type through typeof, then the output of the above example is: number, string (String), Boolean (Boolean), function (functions), object. In addition to the basic data types in these 5, JS also has a type called undefined, which generally exists in the following two cases:

Alert (typeof B);

Variable b is not defined, so JS returns a numeric type of undefined (undefined).

var b;

Alert (typeof B);

At this point, although we define the variable B, in JS, the type of the variable depends only on the value of the variable memory, and the variable B has no value, so its data type is still undefined.

JS is more flexible than restricting the data types of variables, but it can be very confusing if a variable keeps changing the type. So the same variable, it is best to store only one type of data.

  Three, the conversion of the variable type

Variables have not only types, but also conversions between types. If the type of a data does not meet our needs, then a conversion of the data type is required. Let's raise a ' chestnut ' together:

Add two text boxes and a button to the page, and you want the numbers in the text box to add up when you click the button. This function looks simple, if written directly, because the property of value in the TextBox is returned to JS as a string, which causes the two digits of the input to be added to the string instead of the numeric value. At this point, we need to convert the string to a number.

The method of converting a string to a number is parseint ().

Here is an example of parseint ():

var a = ' 1024 '; Alert (parseint (a) +1);

Here we define a for the string, but the value type of data is obtained by parseint conversion, so the output result is 1025. It is important to note that parseint scans the string from left to right, once it finds a character that is not a number, stops working immediately, and returns the preceding character through a numeric type, so the following three cases return the results in order of 1024,1024,nan:

var a = ' 1024px '; var b = ' 1024px24 '; var c = ' abc '; Alert (parseint (a)); Alert (parseint (b)); Alert (parseint (c));

The NaN here is the shorthand for not a number, in short, the result will be returned if JS cannot parse the numbers.

So, our case can be done with the following code:

<script>window.onload=function ()       {        varOtxt1=document.getelementbyid (' Txt1 '); varOtxt2=document.getelementbyid (' Txt2 '); varObtn=document.getelementbyid (' btn1 ');
obtn.onclick=function() {alert (parseint (otxt1.value)+parseint (Otxt2.value));       }; }; </script> <body>     <input id= "Txt1" type= "text"/> <input id= "txt2" type= "text"/> <input id= "btn1" type= "button" Valu e= "sum"/> </body>

Operation Result:

There is a problem here, we do not have any restrictions on the text box, when the user entered the text box is a letter, not a number, the program is not normal execution. Therefore, it is necessary to determine the text box input value through the Parseint method to convert the result is not Nan, if it is Nan, it means that the user entered a value or the two values are not numbers, you need to return to the user a hint.

So the question comes, in JS, Nan is very wonderful:

var a=parseint (' abc ');

var b=parseint (' Def ');

alert (A==B);

At this point, a and B values are Nan, but the execution of this program is actually false, which tells us that in Js, Nan and nan are not equal. In other words, the judgment result is not nan and cannot be compared by = =. Fortunately despair, JS provides a function: IsNaN (), used to detect whether a variable is Nan.

Now let's see:

The effect is as follows when entering letters:

If the user has input is not a number, then the corresponding error box pops up, if the input two values are not error, will pop up the correct answer.

So what happens when you use parseint to convert decimals?

var a= ' 3.5 ';

Alert (parseint (a));

The output result is 3. For parseint, if the converted number is a decimal, it will leave the fractional part, leaving only the integer part.

If we need to use a decimal, please use parseint's brother--parsefloat, there is no difference between the use of methods, you tiger try. When you do not know whether the converted values are integers or decimals, preference is given to using parsefloat, at which point there is no numerical defect even if the variable before the conversion is an integer.

In the type conversion we just talked about, we explicitly tell the computer that we want to convert the data type, which we call an explicit type conversion (also understood as: cast). Similarly, there is a way of converting types that we call implicit type conversions. The simplest example of an implicit type conversion is as follows:

var a=5;

var b= ' 5 ';

alert (A==B);

In theory, the data types are different and the output should be flase. But the answer given by the browser is true. Please make a comparison with the following example:

var a=5;

var b= ' 5 ';

alert (A===B);

At this point, the returned answer becomes false. So the question is, = = and = = = What is the difference between the two?

for the = = operator, it converts the data type of the two before the comparison, whereas the = = = Operator (the equality operator) does not convert the type, directly compared. In the case of non-convertible types, A and B are definitely not equal. So, when comparing a==b, we didn't explicitly tell the computer that we wanted to convert the type A or B, but the computer did it by stealth, which is what we're talking about as implicit type conversions. In addition to this example, there is another case of implicit conversions:

var a= ' 12 ';

var b= ' 5 ';

Alert (A-B);

If this is a+b, the computer will default to the string addition (concatenation) and pop up 125. But if it's a-B, the computer implicitly converts to a numeric type before subtraction, and we get answer 7.

Why does addition not implicitly convert and subtract? Because in the JS + operator itself with the string concatenation and the number of two functions, if the + recognition as a string splicing, a step can be completed, direct stitching can be; but if it is recognized as a number, it takes two steps to complete the calculation, that is: the type is converted first, Then Add. For computers, the path to fewer steps must be chosen, so that addition does not convert implicitly. In JS, the-operator only the function of the number subtraction, at this time, JS has to be implicitly converted.

  Four, variable scope

Variable scope refers to the scope in which a variable can function.

  

function aaa () {var a=12;  } function bbb () {alert (a);  } aaa (); BBB ();

Running this program, there will be an error that the variable A does not have defined within the BBB function. In fact, a is not defined because a is a local variable defined in AAA, and a local variable can only be used within the function that defines it. A concept that is relative to a local variable is a global variable.

var A;

function aaa () {

a=12;

}

function bbb () {

alert (a);

}

AAA ();

BBB ();

The A in this example is declared outside of all functions, and such variables are global variables that can be used anywhere, so they pop up 12 normally.

  Five, closures

On the concept of closures, I suggest you do not have to delve into this stage, if you are interested in the words can Google. As we said, a local variable can only be used within the function that defines it. Well, there is one case exception:

function aaa () {

var a=12;

function BBB ()

{

alert (a);

}

BBB ();

}

AAA ();

When the function BBB is contained within the function AAA, the program can run successfully. This type of writing is called closures. Closures have many high-level applications, of course these are something, we learn slowly. In a closure structure, AAA is called a parent function, and BBB is called a child function. For closures, child functions can use local variables of the parent function. In fact, we've just used closures, such as the Sum function above.

  Six, naming conventions

Naming conventions, that is, how to name functions and variables.

Give the function and the variable name and give your child the name of the same, the theory is can be casually taken, but the actual application may not appear too vulgar too low, otherwise it might cause the old king next door dissatisfaction.

About naming conventions:

Readability--Easy to read

Normative-rule-compliant

Readability represents the name as much as possible to understand. If the code throughout is AAA,BBB,CCC such a name, and just meet the program is relatively large, at this time reading will be a very painful thing.

Normative expression JS has a more commonly known as the naming rules, in most cases using the Hungarian nomenclature or similar method, the principle is:

Type prefix

Capitalize first letter

Common type prefixes in JS:

Type prefixes generally indicate the type of variable storage, so that we can identify what is stored in the variable at a glance, and other people do not randomly change the data type when they get the code, which guarantees the code and better readability. In general, only variables follow the specification of prefixes, while functions do not.

When a variable or function name consists of multiple English words, we usually use the Hump method to name the first letter of each word capitalized, such as Obtnuserlogin, which can be more clearly determine the meaning of the variable.

"JavaScript from getting started to giving up" JS Basics-01

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.