Some summary of JavaScript basics

Source: Internet
Author: User
Tags uppercase letter

A closed package

The definition of "closure" (closure) in various professional literature is very abstract and difficult to read. My understanding is that closures are functions that can read other functions ' internal variables.
Because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function".
So, in essence, a closure is a bridge that connects the inside of the function to the outside of the function.
Function F1 () {
var n=999;
function F2 () {
alert (n);
}
return F2;
}
var result=f1 ();
Result (); 999
The F2 function in the previous section of the code is the closure.

Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times:
Function F1 () {
var n=999;
Nadd=function () {n+=1}
function F2 () {
alert (n);
}
return F2;
}
var result=f1 ();
Result (); 999
Nadd ();
Result (); 1000

The difference between function declaration and function expression in two JS

The function declaration in JS refers to the following form: Functions functionname () {}
Such a way to declare a function, whereas a function expression is like an expression that declares a function, such as: var functionname = function () {}
See these two kinds of writing will produce doubts, these two writing is similar, in the application seems to be also feasible, then they have what difference?
In fact, the parser of JS does not treat function declaration and function expression equally. For function declarations, the JS parser will read first,
Make sure that declarations have been resolved before all code executes, and function expressions, like variables that define other primitive types,
It is parsed only when it is executed to a sentence, so in practice, they will still be different, specifically,
When you define a function by using the form of a function declaration, you can call it after the function declaration, and then you will get an error.

Three values

NaN "non-numeric", with toxicity, bug. The typeof type is number (this is one of the strangest behaviors of the typeof operator).

The. 1+.2 result is 0.30000000000000004.
Use the Math.Round () method to obtain a double-digit precision.
Math.Round ((. 1+0.2) *100)/100 results of 0.3;

"SDXF". IndexOf ("x") in sdxf position: 3
"SDXF". CharAt (4) The 4th letter in SDXF is: F

Type comparison: 1== "1" returns true,1=== "1" returns false.

Variables: i=0, implicitly declared, implicitly declared variables always have global scope, even if the variable is declared in the body of a function function. (It is recommended to declare with the VAR keyword, and it is recommended to declare at the top of the scope)
var i=0; Explicit declaration.
var i; Uninitialized, contains a specific value undefined.

Four objects

Object: An object is a collection of properties, each with a name and a value. A property can contain any type except undefined, which can be assigned a value after the object is created.

Instantiate the object, the first method uses the New keyword:
var myobject=new Object ();
The New keyword will call the constructor, or a more general argument is the constructor. The constructor initializes the newly created object.
constructor function:
function CName (name) {
alert (name);
}

var ccname=new cName ("constructor");

Instantiate an object, the second method uses the literal (this way to create an object more like a hash "hash" or an associative array in another language):
var myobject={};
var domarr={
"Name": "Constructor 2",
"Age": MyObject

}
var nm=domarr["name"];//can be used., as follows
var ag=domarr.age;
alert (nm);
Alert (AG);

Because properties can also be objects, you can nest objects on any layer:
var tem={"name": {"Bbo": {"UU": "H", "DD": "I"}}};
The alert (TEM.NAME.BBO.UU) result is H.

JavaScript is a dynamic language, so to update a property, you only need to re-assign values to the property values. To remove a property, simply use the delete operator and delete the nonexistent property without danger.

JavaScript uses prototype inheritance, which inherits objects directly from other objects, creating new objects. In short, an object inherits properties from another object. Because there are no classes in JavaScript.

For example, a person, JavaScript, is no one in this class, but Zhang San inherits the characteristic "attribute" (eye, nose, age, etc.) of John Doe, which forms the new object "Zhang San".

When creating a new object, note the initialization of the object:
var object1=object2={}//refers to the same object.
var object1={},object2={}//refers to not the same object.

Five functions, closures, variables

We think we should try to avoid using global variables, but some things are necessary, so we'll take some steps to avoid disrupting the global namespace.
One approach is to use a single global variable as the top-level object that contains all the methods and properties in the program or framework. Installation conventions, namespaces are capitalized in all letters, but it is worth noting that constants are also in uppercase format.
bbnn_ppo={};
Bbnn_ppo. clem={
"Name": "Agele",
"Age": "5"
}
Bbnn_ppo. dem={
"Name": "Cdiny",
"Age": "4.5"
}

Another is the use of closures:

Function: A function is a block of code that encapsulates a series of JavaScript statements. The function can either receive the parameter or return a value.
Unlike C # and Java, functions in JavaScript are objects of the first class (first-class).

return value, followed by parameter:
function Calc (x) {
return x*10;
}
Alert (Calc (30));
Result 300.


If the function does not return a specific value, it returns a value of undefined:
var x=2;
Function Calc ()
{
x=x*10;
}
alert (x);//result is 20
Alert (calc ());//result is undefined

The function assigns a value to a variable:
var calc=function (x)
{
return x*2;
}
Alert (Calc (5));//result is 10.
Parentheses are used for the function name, which executes the function and returns the value of the function instead of returning a reference to the function.

To pass a function as an argument to another function:
Function Demo (FN) {
Alert ("This is received:" +FN ());
}
Demo (function () {return "Big Brother"});
The result is "This is received: Big Brother"

Two-type:
Function Demo (FN)
{
Alert ("This is received:" +FN ());
}
Function Calc ()
{
return 2*3;
}
Demo (calc);
The result is "This is received: 6"

Anonymous functions: A particularly important variant is the immediate invocation of a function expression, or a self-executing anonymous function.
The essence of this pattern is to wrap a function expression in a pair of parentheses and call the function immediately.
This technique is very simple, wrapping the function expression in a pair of parentheses will force the JavaScript engine to recognize the function () {} block as a functional expression, rather than the beginning of a function statement.

(function (x, y) {
alert (x+y);
}) (5,6);//The result is 11, and finally the parenthesis (5,6), which can be written in parentheses in front of the

Since this function expression will be called immediately, this pattern is used to ensure that the execution context of a block of code executes in the pre-term effect, which is one of the most important uses of this pattern.
By passing parameters to a function, you can capture the variables in the closures created by the function at execution time.
Closures are such a function: it is in a function body and applies the variables in the current execution context of the function body.

Closure application, and a function that takes another function as the return value:

var x=24;
alert (x); The result is: 24
var message= (function (x) {
return function () {//function as return value
Alert ("X in the closure is:" +x);//The result is: The x in the closure is: 24
}
}) (x);
Message ();//No results
x=12;
alert (x);//The result is: 12
Message ();//The result is: "X in the closure is: 24", regardless of the value of the outer scope x, the closure remembers the value of the variable x when the function was executed.

Execution context: It is an object that code executes in the execution context environment. The "execution context" can be accessed through the This keyword, which is a reference to the current execution context object.
If the code does not exist in a user-defined object or function, it will belong to the global context.
In JavaScript, there are no functions that define a specific "context", which binds the value of their this keyword to the undefined value.
alert (this);//[object Domwindow]

The Eval function settimeout function has its own independent "execution context".

When you start executing a function or method, JavaScript creates a new execution context and enters the function's execution context, and when the function finishes and returns, the control is given to the original execution context.
The current "context" will be preserved when the closure is created, otherwise the current "context" will be collected in front of the garbage.

Scopes and closures:
When discussing scopes, it is important to consider defining the position of variables and the lifetime of the variables. Scope refers to where the variable can be used.
In JavaScript, scopes are maintained at the function level, not at the block level. Therefore, parameters and variables defined using the var keyword are only visible in the current function.

Nested functions: In addition to the this keyword and parameters, nested functions can access variables defined in external functions. This mechanism is implemented by closures, which means that even after an external function interprets execution, the inner nested function continues to maintain its reference to the external function. Closures also help in company namespace conflicts.
Each time a package (enclosed) function is called, although the code of the function changes monthly, JavaScript creates a new scope for each invocation.
function getcom (value) {
return function (value) {
return value;
}
}
var a=getcom (), b=getcom (), c=getcom ();
Alert (A (0));//result is 0, each call creates a new scope
Alert (b (1));//result is 1
Alert (c (2));//result is 2
alert (a===b);//false;
});

When you define a standalone function (no object is bound), the This keyword is bound to the global namespace.
As a direct result, when a function is created within a method, the inner function's keyword this is bound to the global namespace instead of binding the method.
To solve this problem, you can simply assign the This keyword of the wrapping method to a middle variable named that.
var obj={};
Obj.mathod=function () {
var that=this;
this.counter=0;
var count=function () {
That.counter+=1;
alert (that.counter);//The value of the upper function definition cannot be passed in
}
Count ();//result is 1;
Count ();//result is 2;
alert (this.counter);//When the intrinsic function is not called, the value is 0; now the value is 2
}
Obj.mathod ();
(Personal understanding: A thief, a beggar, want to eat food (inner world = internal function), the Thief into the host (home = external function), but can not find food (food = external function variables), Beggar side at home (outside function) begging, but got food (function variable), So thieves want to get food must detour to outside to get food)

There is no official access-level syntax in JavaScript, and JavaScript does not have access-level keywords similar to private or protected in the Java language. By default, members in an object are common and accessible. In JavaScript, however, you can achieve access-level effects that are similar to private or public properties. To implement a private method or property, use a closure:
function Retun () {
var chaer= "hard";//Private

This.oo=function () {//Closures
return chaer;//Public
}
}
var dem=new retun ();
alert (Dem.chaer);//undefined
Alert (dem.oo ());//Bad luck

This.oo () is a proprietary method of function Retun that can access private members in Retun. In addition, the Chaer variable is "private" and his value can only be accessed through a proprietary method


Using modules: Similar to private and proprietary access levels, there is no built-in package syntax in JavaScript. Module mode is a common encoding mode.

ttmmoon={};//Creating namespaces
Ttmmoon.teme= (function () {//functions expression
var destion= "", molde= "", fulle= "";//Private Member
Public access Methods
return{
The setting device
Setdestion:function (dest) {
This.destion=dest;
},
Setmodl:function (Mold) {
This.molde=mold;
},
Setfulle:function (Full) {
This.fulle=full;
},
Accessors
Getdestion:function () {
return this.destion;
},
Getmodl:function () {
return This.molde;
},
Getfulle:function () {
return This.fulle;
},
Other Members
Tostring:function () {
Alert (This.getmodl () + "-Hi, China" +this.getfulle () + "-Thank you! "+this.getdestion ());
}
The initialization process is performed here
}
}());
var mytimeus=ttmmoon.teme;
Mytimeus.setmodl ("My name is Joy,");
Mytimeus.setfulle ("I'm Happy");
Mytimeus.setdestion ("I'll be back.") ");
Mytimeus.tostring ();

});

Vi. data types, javascript practices

Extension Type:
JavaScript supports binding methods and other properties to built-in types, such as String, numeric, and array types. Like any other object, a string object also has the prototype property. Developers can extend some convenient methods for string objects. For example, string does not convert the string false or True to a Boolean value method.
You can add this functionality to a string object using the following code:
String.ptrototype.boolean=function ()
{
Return "true" ==this;
};
var t= ' true '. Boolean ();
var f= ' false '. Boolean ();
Alert (t);//ture
alert (f);//false

Simplified two:
Function.prototype.mathod=function (Name,func)
{
This.prototype[name]=func;
return false;
}
String.mathod ("Boolean", function () {
Return "true" ==this;
})
"True". Boolean ();//true

Best Practices for javascript:

1. Use the parseint () function to convert a string to an integer, but ensure that the cardinality is always specified. A better approach is to use the unary operator (+) to convert the string to a numeric value:
Good:parseint ("010", 10);//Convert to Decimal
better:+ "010";//Efficient

2. The equivalent (= = =) operator is used to compare two values to avoid unexpected type conversions.
Type comparison: 1== "1" returns true,1=== "1" returns false.

3. When defining object literals, do not use commas at the end of the last value:
var obj={
Name: "Any",
Age: "20"
}

4. Do not use the WITH statement.
5. It is very inefficient to create functions in a loop with caution.
6. The eval () function can accept a string and treat it as JavaScript code execution. The use of the Eval () function should be limited, and it is easy to introduce a variety of serious security issues in your code.
7. Use a semicolon as the end of the statement, especially useful when refining the code.
8. The use of global variables should be avoided. You should always use the VAR keyword to declare variables. Wrap your code in anonymous functions, avoid naming conflicts, and use modules to organize your code.
9. Use an uppercase letter for the function name to indicate that the function will be the constructor of the new operator, but do not use the first letter capitalization for the function name of any other function.

Some summary of JavaScript basics

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.