Subject to a

var test = function (x) {
    var y = new Date();            
    y = y.getMonth() + x;    
    return y.toString();
};
console.log(test(3));
console.log(x);
Copy the code

5. X is not function

GetMonth () + 1 = 3; getMonth() + 1 = 3; y.getMonth() = 2; X is 3, so the first result is 5. The second error is reported because x is an undefined parameter.

Program time

Output today’s date as YYYY-MM-DD, for example, today, January 1, 2019, 2019-01-01.

function getTime(){
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    function addZero(num){
        return num >= 10 ? num : '0'+num;
    }
    return y + The '-' + addZero(m) + The '-' + addZero(d);
}
var res = getTime();
console.log(res);
Copy the code

Js runtime mechanism

Js is mainly used to interact with users and manipulate the DOM. Decisions can only be single threaded. If there are two threads, one for adding content to a DOM node and the other for removing it, which thread should the browser focus on?

Single threading means that all tasks need to be queued until the first one is finished before the next one can be executed. All tasks are divided into two types, one is synchronous tasks (tasks queued to be executed on the main thread, and later tasks can be executed only after the previous tasks are completed). The other is asynchronous tasks (tasks that do not enter the main thread but enter the task queue). An asynchronous task is executed only when the task queue notifies the main thread that it is ready to execute.

Synchronizing tasks on the main thread forms an execution stack. The code in the stack calls various external apis and adds various events

An asynchronous task is on a task queue (a first-in, first-out data structure that is read first by the main thread)

Task queues (click,load, callback functions, IO device events, mouse clicks, page scrolls, etc.). You can also place timed events

Whenever the main thread is empty, it reads the task queue. The process repeats itself.

Timer: timing the amount of time before some code is executed. That is, code that executes on time.

Subject to a

var arr = ['First output'.'Second output'.'Third output'];
for (var i = 0; i < arr.length; i++) {
    setTimeout(function () {
        console.log(arr[i]);
        //获取数组中下标不存在的数,结果是undefined
    }, i * 2000)
}
Copy the code

Answer: undefined

Resolution:

The for loop is in the main thread, and the setTimeout callback is an asynchronous method. In the task queue, when I =0, the loop body code is executed, and setTimeout waits in the task queue. If I ++, I = 1, setTimeout will wait in the task queue. If I ++, I =2, setTimeout will wait in the task queue. If I ++, I = 3, arr.length will be 3. The delayed callback setTimeout is executed to read the code in the task queue. SetTimeout => At this time I is 3, arr[3] array has no subscript 3, so print undefined 3 times. The printing time is 0s,1s and 2s respectively.

Topic 2

for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
        console.log(i);
    }, 0);
}
Copy the code

Answer: five sixes

The for loop is in the main thread, and the setTimeout callback is an asynchronous method. In the task queue, the code in the task queue is executed when the for loop ends. At this point there are five setTimeout methods waiting in the queue. I is 6. So print five 6’s.

Topic 3

for (var i = 1; i <= 5; i++) {
    if (i == 1) {
        setTimeout(function() { console.log(i); }, 0); }};Copy the code

Answer: 6

The for loop is in the main thread, and the setTimeout callback is an asynchronous method. In the task queue, the code in the task queue is executed when the for loop ends. If the main thread has a judgment I = 1, there is only one callback waiting in the queue. The for loop ends with I equal 6. So you do this setTimeout and the output I is 6.

What is a callback function?

One function is passed as an argument to another function. Callback functions are also called callback mode. For example:

$("#btn_1").click(function() {
  alert("Btn 1 Clicked");
});   
Copy the code
function1. Define an anonymous function as a callbackfunction getFn(fn){
    console.log(111);
}
getFn(function(){
    console.log('I'm an anonymous function'); }) 2. Define named functions that are passed as arguments to another functionfunctionlogin(data){ console.log(123); } A function that takes two arguments, followed by a callback function.functiongetInfo(options,callback){ callback(options); } when getInfo is called, pass login as an argument to it. getInfo({name:'admin',psw:'123'},login);

Copy the code

Anonymous functions

(function () { var a = b = 1; console.log(a); }) ()

console.log(a, b);

Answer: 1 error

Var a = 1; b = 1; A is a local variable, b is a global variable. 1 if b is printed before console.log(a,b). And print an A outside to report an error

Function declarations are different from function expressions

The sum (1, 2); / / 3function sum(x,y){
     alert(x+y);
}
Copy the code
Ss (1, 2); // undefined is not afunction
 var ss = function(x,y){
     alert(x+y);
 }
Copy the code

The parser reads the function declaration first. Functional expressions, on the other hand, are not actually parsed until the parser reaches the line on which they are expressed.

Understand anonymous functions in depth

(function(){// define and immediately call // this is a function expression. The final () means to call the function immediately. }) ()Copy the code
The following two errors are reportedfunction foo(){ /* code */ }();

function foo(){ /* code */ }( 1 );
Copy the code

To implement the above code, you must assign. Change to the following two can be used

var aa = function(x){ alert(x); } (5); / / 5Copy the code
(function(x){ alert(x); } (5))Copy the code

Self-executing function

Definition and invocation rolled into one.

(function() { /* code */ } ()); // This is recommended.function() { /* code */ })(); // But this can also be usedCopy the code
var i = function () { return 10; } ();
true && function () { /* code */ } ();
0, function () { /* code */ } ();
!function () { /* code */ } ();
~function () { /* code */ } ();
-function () { /* code */ } ();
+function() { /* code */ } (); // There is another case where the new keyword can also be used, but I am not sure how efficient it is newfunction () { /* code */ }
new function() {/* code */} () {/* code */} ()Copy the code

A single anonymous function will report an error that it cannot run or be called

function() {return 'lee';
}
Copy the code

Self-execution by expression

(function(){
    alert('lee'); }) ();Copy the code

Assign anonymous functions to variables

var cat = function() {return 'lee'; } alert(cat()); / / callCopy the code

Assigns the self-executing return value of the anonymous function to the variable

var box = (function() {return 'lee'; }) (); alert(box);Copy the code

Pass arguments to self-executing anonymous functions

(function(num){ alert(num); }) (100);Copy the code

The title

var test = (function(a) {
  this.a = a;
  return function(b) {
      returnthis.a + b; }} (function(a, b) {
  return a;
}(1, 2) ));

console.log(test(4));
Copy the code

Answer: 5

Resolution:

(function(a, b) {
  returna; }(1, 2) => 1Copy the code
var test = (function(a) {
  this.a = a;
  return function(b) {
      returnthis.a + b; }} (1))test= > (function(a) {
  this.a = a;
  return function(b) {
      returnthis.a + b; }} (1))test() = >function(b) {
      return this.a + b;
  }
  
test(4) => b = 4; Up here a = 1; this.a + b = 5; The anonymous function calls the window to which this pointsCopy the code