Lambda function in TypeScript

The author of this article is the front-end development engineer of 360 Qiwu Troupe

Lambda function in TypeScript

Lambda function aka arrow function

Arrow function expression syntax is shorter than function expression syntax, and does not have its own this , arguments , super or new.target. Arrow function expressions are more suitable for places where anonymous functions are expected , and it cannot be used as a constructor.

The arrow function provided by the ES6 version of TypeScript is a shorthand syntax for defining anonymous functions, which is used in function expressions and omits the function keyword. Arrow functions have the this key syntax role.

What arrow functions do :

  • When we don't need to continue to enter the function;

  • It lexically captures the meaning of this keyword;

  • It captures the meaning of the parameters lexically.

grammar

can be divided into three parts

  • Parameters: Functions can have parameters or not

  • Arrow symbol: =>

  • Statement: Represents a set of instructions for a function

If you use the arrow function notation, you don't need to use the function keyword. Parameters are passed in (), function expressions are in {}.

basic grammar

(param1, param2, ..., paramN) => { statements }
(param1, param2, ..., paramN) => expression
//当只有一个参数时,圆括号可以省略,可选的
(singleParam) => { statements }
//省略圆括号
singleParam => { statements }
//没有参数的函数应该写成一对圆括号
() => { statements }

ES6 provides other ways to write anonymous functions, syntactic sugar.

//sum 是一个箭头函数, a、b 是参数,a、b后面的:number 是参数类型   : number 是返回类型
箭头符号分隔了函数参数和函数体
const sum = (a: number,b: number): number => {
  return a+b;
}
 console.log(sum(20,30))// return 50

When the function body is not needed and only a value is returned, the return keyword and the outer curly braces can be omitted.

const fun = () => 'value';

Arrow function usage in class

class Student {
    stucode: number
    stuname: string
    //构造函数  构造Student对象
    constructor (code: number, name: string) {
        this.stucode = code
        this.stuname =name
    }
    studetail = () => {
      console.log('stucode:' + this.stucode + '\nstunam:' + this.stuname )
    }
}

export { Student }

import { Student } from '@/views/Student'

 let stu = new Student(100, 'jorn')
 stu.studetail()

Arrow functions with parameters

const fun = (item: number ) => item*2;
//当只有一个参数时候,可以省略参数外面的括号
const fun = item => item*2;
//多个参数传递
const fun = (item: number,item1: number, item2: boolean) => {
let value;
if(item2){
 item++;
 value= item;
}else {
item1 ++;
value = item1;
}
  return  value;
}

Arrow functions cannot be used as constructors, and will throw an error when used with new. There is also no prototype property. The yield keyword generally cannot be used in arrow functions (unless nested inside a function where it is allowed). Therefore, arrow functions cannot be used as function generators.

function body

Arrow functions can have a "shorthand" or common "block"

//简写函数 省略 return
var func = x => x+x ;
//常规写法
var func = (x,y) => { return x+y; };

return object literal

记住用 params => {object: literal}This simple syntax of returning object literals doesn't work.

// 下面这样行不通
var func =  () => { foo: 1 };

var func = () => { foo: function() {} };

This is because the code inside curly braces ({}) is parsed as a sequence of statements (ie foo is considered a label, not part of an object literal). So, remember to wrap the object literal in parentheses.

var func = () => ({foo: 1});

new line

Arrow functions cannot have a newline between the argument and the arrow.

It cannot be written as the following, which is wrong

var func = ()
=> 1;

However, a line break after '=>' is possible

var func = (a,b,c) =>
{
1;
}

Arrow functions can also use closures

//标准的闭包函数
function A(){
    var i=0;
    return function b(){
    return (++i);
    };
};

var v =A();
v();//1
v();//2

// 箭头函数体的闭包(i=0 是默认参数)
var Add = (i=0) => { return (() => (++i) )};
var v = Add();
v();//1
v();//2

因为只有一个返回值,return 及括号() 也可以省略
var Add = (i=0) => () => (++i);

- END -

About Qi Wu Troupe

Qi Wu Troupe is the largest front-end team of 360 Group, and participates in the work of W3C and ECMA members (TC39) on behalf of the group. Qi Wu Troupe attaches great importance to talent training, and has various development directions such as engineers, lecturers, translators, business interface people, and team leaders for employees to choose from, and provides corresponding technical, professional, general, and leadership training course. Qi Dance Troupe welcomes all kinds of outstanding talents to pay attention to and join Qi Dance Troupe with an open and talent-seeking attitude.

5ffac450f447525cf04be41cb26c9b00.png

Guess you like

Origin blog.csdn.net/qiwoo_weekly/article/details/130787711