To learn about js, you must know the [recommended] concepts of these js functions.

Source: Internet
Author: User

To learn about js, you must know the [recommended] concepts of these js functions.

Function Creation Method

 1. Declaration MethodFor example, function consoleTip () {console. log ("tip! ");}

 2. expression modeFor example: var consoleTip = function () {console. log ("tip! ");}

Differences between the two methods:

1. The expression method is suitable for defining a function that only uses one time. The declared function does not have this restriction. Of course, this difference is not absolute. It is only applicable to coding specifications;

2. A declared function can be defined either before or after a function call. A function defined by an expression can only be defined before a function call;

Function Parameters

Function parameters include the form parameter and real parameter. The form parameter is the parameter when the function is defined. The real parameter is the parameter passed in when the function is called. Because Javascript is a weak type language, the type is not specified for the form parameters of js functions.

The parameters and real parameters of the js function can be inconsistent. When the number of parameters is smaller than that of the real parameter, the value of the parameter that is not passed is undefined. Note that the default value can be specified for the parameter but only for the function body. When the number of parameters is smaller than that of the real parameter, to reference redundant real parameters in a function, you must obtain the real parameters through the real parameter object arguments. In the function body, arguments is the reference of the real parameter object, and the real parameter object is an array object, each item of the array object corresponds to the parameters passed in when the function is called.

PS:The real parameter object has two special attributes: callee and caller. The callee attribute represents the currently executed function, and the caller attribute represents the function that calls the currently executed function. The caller attribute is not a standard attribute, not all browsers support this function. A typical example of using the callee attribute is the recursive call of an anonymous function, for example, defining a factorial function:

var fact = function(x){  if(x <= 1) {  return 1; }else{  return arguments.callee(x-1)*x; }};

Function Scope

Variables declared in the function (including function parameters) are visible throughout the function body, including nested functions that are invisible outside the function; the variables defined in the function body overwrite the global variables with the same name;

A feature in the function scope is very important, that is, "declare in advance", which means that variables declared at any position inside the function are visible at any position inside the function body, this is because the js engine precompiles all the variable declarations in the function to the top of the function body.

For example:

var scope = "outter";!function(){ console.log(scope); //undefined var scope = "inner"; console.log(scope); //inner}();console.log(scope);  //outter

Note:

UndefinedThe scope of the function is declared in advance. scope is declared at the top of the function but not assigned a value. Therefore, the scope value is undefined.

InnerThe scope is declared within the function body and assigned a value.

OutterThe variables defined in the function body overwrite the global variables with the same name, but do not affect the value of the global variables.

Constructor

A constructor is used to initialize a newly created object. For example, var ary = new Array ();

Differences between constructors and common functions:

1. There are differences in the name of a function. The name of a constructor is usually the first character in upper case and the first character in lower case in the name of a common function;

2. Differences in calling methods. constructor is called using the new keyword, while common functions are called directly.

Execute function now

Combining Function Definition and function execution is to execute a function immediately, also called a self-executed function.

Note the following two points: 1. The function definition is limited to the functions defined in the expression mode; 2. The function execution is actually an operation on the function expression, so the unary operators can execute the function.

In this way, multiple methods can be written to execute the function immediately:

(function(){console.log("IIFE");}());(function(){console.log("IIFE");})();!function(){console.log("IIFE");}();void function(){console.log("IIFE");}();~function(){console.log("IIFE");}();....

Parameters are acceptable for immediate function execution. The preceding statements are acceptable, but the first method is recommended for coding specifications. The jQuery library uses the first method.

So what are the functions of self-execution? In summary, there are two common types:1. Save the parameter context; 2. Use it as the namespace.

Use 1Application scenarios: asynchronous functions are executed in a loop, and function parameters change cyclically.

/*** Example 1 * incorrect syntax, because jQuery's post method is asynchronous and has ten cycles. The post method runs ten times in parallel. * The loop is faster than the post method, the I value passed in is changed to 10, that is, the index received by the server is 10 */for (var I = 0; I <10; I ++) {$. post (url, {index: I}, function () {}) ;}/ *** is written correctly, so that for immediate function execution in the loop body, parameters for each loop are different. Execute the function immediately * each time a function is executed, a function context environment is created. The variable values in this context environment are not affected by the outside world. * Ten context environments will be created ten times in a loop, and the I value of each context is different. In this case, * although the post method is an asynchronous method, it is executed in each context environment, that is to say, the loop is ten times. * The post method is executed once in each of the ten context environments, the index parameters used in the post method are different each time. * The index value received by the server end is 10 to 9 values */for (var I = 0; I <10; I ++) {(function (index) {$. post (url, {index: index}, function () {});} (I);}/*** Example 2 * incorrect syntax, ten 10 will be output eventually, because the statement of the loop body will be delayed to execute */for (var I = 0; I <10; I ++) {setTimeout (function () {console. log (I) ;}, 100) ;}// write the statement correctly. Finally, 10 to 9 values are output. The principle is the same as for (var I = 0; I <10; I ++) {(function (x) {setTimeout (function () {console. log (x) ;}, 100) ;}( I ));}

Use 2Application scenarios: You need to write a public module, which is used in many places. However, make sure that the variables and functions used in the public module do not cause pollution to other modules, in this case, this public module requires a namespace different from that of other modules.

Case 1: Create the jQuery plug-in to ensure that the created jQuery plug-in is valid in the jQuery namespace so that each jQuery object can be used.

(function($){ $.fn.changeStyle = function(colorStr){  this.css("color",colorStr);    return this; }}(jQuery));

Case 2: Create an object with private variables and private methods.

var obj = (function(){ var privateAttr,  publicAttr;   function _setPriAttr(){  privateAttr = "private"; }   function getPriAttr(){  return privateAttr; }   return {  attr:publicAttr,     getAttr:function(){   getPriAttr();  } }}());

Objects created in this way expose attributes and methods by executing the return Statement of the function immediately, and ensure that the attributes and methods of objects are not exposed, it cannot be accessed outside the object.

Conclusion: in fact, the principles of use 1 and use 2 are the same. They both use the concept of function scope.

References: js authoritative guide

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.