【Python全栈-JavaScript】JavaScript匿名函数的用法总结

JavaScript匿名函数的用法

最常用的匿名函数写法:

(function() {
        alert('water');
    })();

// 当然也可以传参数
(function(o) {
   alert(o);
})('soil');

不常用的写法:

    ~(function(){
        alert('desk');
    })();  //写法有点酷~

    void function(){
        alert('computer');
    }();  //据说效率最高~

    +function(){
        alert('phone');
    }();

    -function(){
        alert('mouse');
    }();

    ~function(){
        alert('sock');
    }();

    !function(){
        alert('fans');
    }();

    (function(){
        alert('paper');
    }());  //有点强制执行的味道~

箭头函数 补充:

=>  是es6语法中的arrow function

(x) => x + 6

//相当于

function(x){
    return x + 6;
};

x => x * x   相当于 function(x){return x*x}

箭头函数相当于 匿名函数, 简化了函数的定义。 语言的发展都是倾向于简洁 对人类友好的, 减轻工作量的。 

箭头函数有两种格式, 一种只包含一个表达式,没有{…} 和 return 。 一种包含多条语句, 这个时候{} return 就不能省略

x => {
     if (x>0){
         return x*x
     }else{
        return x
     }
}

如果有多个参数就要用 ():

// 两个参数返回后面的值
(x, y) =>x*y + y*y

//没有参数
() => 999

// 可变参数
(x, y, ...rest) =>{
    var i,sum = x+y;
    for (i=0;i<rest.length;i++){
        sum += rest[i];
    }
    return sum;
}

如果要返回一个单对象, 就要注意, 如果是单表达式, 上面一种会报错, 要下面这种

// 这样写会出错
x => {foo:x} // 这和函数体{}有冲突
// 写成这种
x => ({foo:x})

箭头函数中this 指向

箭头函数 看起来是匿名函数的简写。但是还是有不一样的地方。 箭头函数中的this是词法作用域, 由上下文确定

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            return new Date().getFullYear() - this.birth; // this指向window或undefined
        };
        return fn();
    }
};

箭头函数修复了this的指向, this 总是指向词法作用域, 也就是外层调用者obj:

var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
obj.getAge(); // 25

如果使用箭头函数,以前的那种hack写法 就不需要了: 
var that = this;

由于this 在箭头函数中已经按照词法作用域绑定了, 所以使用 call 或者apply() 调用函数的时候, 无法对this 进行绑定, 即 传入的第一个参数被忽略:

var obj={
    birth:2018,
    getAge:function(year){
    var b =this.birth;//2018
    var fn = (y)=>y-this.birth //this.birth 仍然是2018
    return fn.call({birth:200},year)
}
}
obj.getAge(2020)

参考:https://blog.csdn.net/zls986992484/article/details/53838497

https://blog.csdn.net/yangxiaodong88/article/details/80460332

原文地址:https://www.cnblogs.com/XJT2018/p/11047186.html