TypeScript arrow functions

Recognize arrow functions

var fun1 = function(a:number, b:number=2):number{
    return a+b;
}

function fun2(a:number, b:number):number
{
    return a+b;
}

// Use ES6 arrow function syntax to define the function, delete the "function" keyword and function name of the original function, 
// and use "=>" to connect the parameter list and the function body.

var fun3 = (a:number, b:number):number=>{
    return a+b;
}

(a:number,b:number):number =>{
    return a+b;
}


//===================无参
var fun5 = function(){
    //do something.
}
var fun6 = ()=>{};

// ================= Single parameter 
var fun7 = function (a: number) {}
 var fun8 = (a: number) => {}
 // var fun9 = a => {}; /// js ok, but ts will compile error


// If there is only one expression, you can omit "{}" and "return" 
// / If you include multiple statements, you cannot omit "{}" and "return" 
let fun9 = () => "hello" ;
let fun10 = ()=> {return 'hello'};
let fun11 = (a:number, b:number)=> a+b;
let fun12 = (a:number, b:number)=> {return a+b};
let fun13 = (a:number)=>{
    a=a+1; 
    return a;
};

// fun14 => {key:x};
//y => ({key:y});
(x:number) => ({key:x});

let fun15 = (x:number) => ({key:x});
console.dir (fun15);

let fun16 = (a:number)=>{
    a ++;
    return a;
}
fun16(100);
console.log(fun16(100));



// =================================== 
var Person = {
    firstName:"hello",
    lastName:"world",
    getFullName:function(firstName:string){    
        console.log(this);
        var first = this.firstName 
        
        var fn = (f:string)=>{
            console.log(this);
            return f+this.lastName;
        }

        return fn.call({firstName:'hh'}, firstName);
    }
}

console.log(Person.getFullName('hi')); /// hiworld


// =================================== 
var obj = {
    array:[1,2,3],
    sum:()=>{
        console.log("sum:");
        return (i:number,j:number)=>i+j;
    }
}
let fun17 = obj.sum();
//console.log(fun17(5,6));
console.log(obj.sum()(2,3)); // 5 

 

Guess you like

Origin www.cnblogs.com/music-liang/p/12723964.html