Handler and scope and abnormal

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

JS syntax

function

function 函数名(参数列表) {
    函数体;
    return 返回值; 
}

function add(x,y){
    return x+y; 
}
console.log(add(3,5));

Function expression

Use an expression to define the function name, the expression can be omitted, if the function name is not omitted, can only be used inside this function.

// 匿名函数
const add = function(x, y){
    return x + y;
};
console.log(add(4, 6));

// 有名字的函数表达式
const sub = function fn(x, y){
    return x - y;
};
console.log(sub(5, 3));
//console.log(fn(3, 2)); // fn只能用在函数内部

// 有名字的函数表达式
const sum = function _sum(n) {
    if (n===1) return n;
    return n + _sum(--n) // _sum只能内部使用
}
console.log(sum(4));

Differences functions, anonymous functions, function expressions

  1. Functions and anonymous functions are the same in essence, is a function of the object, but the function has its own identifier - function name, anonymous function need the help of other identifiers only.
  2. The difference is that function declaration upgrade, will not function expression.
console.log(add(4, 6));
// 匿名函数
function add (x, y){ // 声明提升
    return x + y;
};

//console.log(sub(5, 3)); //sub未定义
// 有名字的函数表达式
const sub = function (x, y){
    return x - y;
};
console.log(sub(5, 3));

Higher-order functions

Higher-order functions: functions as arguments or returns a function

A complete counter counter

const counter = function (){
    let c = 0;
    return function(){
        return ++c;
    };
};

const c = counter()
console.log(c())
console.log(c())
console.log(c())

A complete map function: some processing may be any one of the elements of the array

const map = function(arr,fn) {
    let newarr = [];
    for (let i in arr){
        newarr[i] = fn(arr[i]);
    }
    return newarr
}

console.log(map([1,2,3,4], function(x){return ++x}));

Attached Builder version counter for reference purposes only

const counter = (function * () {
    let count = 1;
    while (true)
        yield count++;
})();

console.log(counter.next())
console.log(counter.next())

Arrow function

Arrow function is an anonymous function, it is a more streamlined format.
Change the example above you function as a function of the arrow

// 以下三行等价
console.log(map([1,2,3,4], (x) => {return x*2}));
console.log(map([1,2,3,4], x => {return x*2}));
console.log(map([1,2,3,4], x => x*2));

Arrow function parameters

  1. If a function has no parameters, using ()
  2. If only one parameter, the parameter list can omit the parentheses ()
  3. A plurality of parameters can not be omitted parentheses, and using commas to separate

Arrow function return value

  1. If the function portion multiple rows, it is necessary to use {}, if there are return values ​​return.
  2. If only one line statement, you can omit the braces and return at the same time.
  3. As long as there is a return statement, we can not omit the braces. console.log (map ([1,2,3,4], x => {return ++ x})), there must return braces.
  4. If only one non-return statement, together with the braces, it would function without a return value, for example, the console.log (Map ([1,2,3,4], X => X { 2})); plus the braces, it is not equivalent to = X> X return { 2}. Therefore, remember x => x * 2 this correct form on the line.

Function Arguments

General parameters

A parameter accounting for a position, support default parameters

const add = (x,y) => x+y;
console.log(add(4,5));

// 缺省值
const add1 = (x,y=5) => x+y;
console.log(add1(4,6));
console.log(add1(4));

So, if there is such a function

const add2 = (x=6,y) => x+y;

Is this allowed? Try to use it

console.log(add2());
console.log(add2(1));

console.log(add2(y=2,z=3)); // 可以吗?

Add2 call the above results were
NaN, NaN, 5
Why?

  1. JS and did not pass parameters Python keywords
  2. JS position parameter corresponding to just do
  3. JS the position is not limited to default parameters
    ADD2 () corresponds to the Add (. 6, undefined)
    ADD2 (. 1) corresponding to the Add (. 1, undefined)
    ADD2 (Y = 2, Z =. 3) corresponds add2 (2,3), because there is no keyword JS mass participation, but it's an assignment expression has value, y = 2 is 2, z = 3 3 is
    recommended, default parameters wrote back, this is a good habit.

Variable parameter (rest parameters remaining parameters)

... denotes a variable parameter used JS (Python by collecting a plurality of parameters *)

const sum = function (...args){
    let result = 0;
    for (let x in args){
        result += args[x];
    }
    return result;
};

console.log(sum(3,6,9))

arguments object

All parameters of the function keys will be stored in one of the arguments for dictionary objects

(function (p1, ...args) {
    console.log(p1);
    console.log(args);
    console.log('----------------');
    console.log(arguments); // 对象
    for (let x of arguments)
        console.log(x);
})('abc', 1,3,5)

Before ES6, arguments should be the only variable parameter
ES6 start is not recommended, it is recommended to use variable parameters. In order to retain compatibility
note, use the arrow functions, take to the arguments is not what we want, as follows

((x,...args) => {
    console.log(args); // 数组
    console.log(x);
    console.log(arguments); // 不是传入的值
})(...[1,2,3,4]);

Parameters deconstruction

And like Python, Js provides the parameters deconstruction, still uses symbols to deconstruct ...

const add = (x, y) => {console.log(x,y);return x + y};
console.log(add(...[100,200]))
console.log(add(...[100,200,300,3,5,3]))
console.log(add(...[100]))

Js deconstruction support parameters, the number of parameters and the number of values ​​need not correspond deconstruction

Function return value

return 1,2 python may be used to return multiple values, a value is in essence, is a tuple. Js in it?

const add = (x, y) => {return x,y};
console.log(add(4,100)); // 返回什么?

Value of the expression:
Class C language, there is a concept - the value of the expression
value of the assignment expression: the value of the right side of the equal sign
comma value of the expression: C-like language, supports comma expression, comma expression the value is the value of the last expression

a = (x = 5, y = 6, true);
console.log(a); // true

b = (123, true, z = 'test')
console.log(b)

function c() {
    return x = 5, y = 6, true, 'ok'; 
}

console.log(c()); // ok

So, JS return value of the function is still the single value

Scope

// 函数中变量的作用域
function test(){
    a = 100;
    var b = 200;
    let c = 300;
}
// 先要运行test函数
test()

console.log(a);
console.log(b); // 不可见
console.log(c); // 不可见

// 块作用域中变量
if (1){
    a = 100;
    var b = 200;
    let c = 300; 
}

console.log(a);
console.log(b);
console.log(c); // 不可见

function is a function definition, is an independent scope, wherein the defined variable is not visible outside the function
var a = 100 can enhance statements, non-functional block may break the scope of
a = 100 can not ascend implicit declaration statements, in under "strict mode" to be wrong, but can be variable implicitly declared as a global variable. Recommended to use less
let a = 100 can not raise statement, but can not break any block scope. Recommended Use

function show(i, arg) {
    console.log(i, arg) 
}

// 作用域测试
x = 500;
var j = 'jjjj';
var k = 'kkkk';

function fn(){
    let z = 400;
    {
        var o = 100; // var 作用域当前上下文
        show(1, x);
        t = 'free'; // 此语句执行后,t作用域就是全局的,不推荐
        let p = 200;
    }
    var y = 300;
    show(2,z);
    show(3,x);
    show(4,o);
    show(5,t);
    //show(6,p); // 异常,let出不来上一个语句块
    {
        show(7,y);
        show(8,o);
        show(9,t);
        {
            show(10,o);
            show(11,t);
            show(12,z);
        }
    }

    j = 'aaaa';
    var k = 'bbbb';
    show(20, j);
    show(21, k);
}

// 先执行函数
fn()

show(22, j);
show(23, k);

//show(13,y); // 异常,y只能存在于定义的上下文中,出不了函数
show(14,t); // 全局,但是严格模式会抛异常

//show(15,o) // 看不到o,异常原因同y

show(16,z); // 变量声明提升,var声明了z,但是此时还没有赋值
var z = 10;

const m = 1
//m = 2 // 常量不可以重新赋值

Strict Mode: "use strict" ;, this statement into a function of the first line, the first line of the script or js

abnormal

Throw an exception

Js anomaly same syntax and Java, use the keyword throw throw
using the throw keyword can throw any object exception

throw new Error('new error');
throw new ReferenceError('Ref Error');
throw 1;
throw 'not ok';
throw [1,2,3];
throw {'a':1};
throw () => {}; // 函数

Catch the exception

try ... catch statement to catch the exception
try ... catch ... finally statement to catch exceptions, finally ensure that the final execution must
be noted here that it does not support the type of catch that is at most a catch statement. You may be in a catch statement block, the discretion exception

try {
    //throw new Error('new error');
    //throw new ReferenceError('Ref Error');
    //throw 1;
    //throw new Number(100);
    // throw 'not ok';
    // throw [1,2,3];
    // throw {'a':1};
    throw () => {}; // 函数
} catch (error) {
    console.log(error);
    console.log(typeof(error));
    console.log(error.constructor.name);
} finally {
    console.log('===end===') 
}

Symbols Type

ES6 offer Symbol type, with native type

let sym1 = Symbol()
let sym2 = Symbol('key1')
let sym3 = Symbol('key1')
console.log(sym2 == sym3) // false,symbol值是唯一的
  1. As a key attribute of an object
let s = Symbol()
let t = 'abc'
let a = {
    [s]:'xyz', // symbol做key,注意要使用中括号,这个key一定唯一t:'ttt', 
    [t]:'ooo'
}

console.log(a)
console.log(a[s])
a[s] = 2000
console.log(a[s])
  1. Construction of constants
// 以前用法
var COLOR_RED = 'RED';
var COLOR_ORANGE = 'ORANGE';
var COLOR_YELLOW = 'YELLOW';
var COLOR_GREEN = 'GREEN';
var COLOR_BLUE = 'BLUE';
var COLOR_VIOLET = 'VIOLET';

// 现在
const COLOR_RED = Symbol();
const COLOR_ORANGE = Symbol();
const COLOR_YELLOW = Symbol();
const COLOR_GREEN = Symbol();
const COLOR_BLUE = Symbol();
const COLOR_VIOLET = Symbol();

Guess you like

Origin blog.csdn.net/weixin_44800244/article/details/94892499