ES6中Function的新特性

在ES6中,函数的参数可以设置默认值。

实参为null,形参为null
实参没有参数或者为undefined,形参为默认值。

(function(a, b = 10, c = 3, d = 4, e = 5) {
    console.log(a, b, c, d, e)
})(1, 2, undefined, null)

// a => 1
// b => 2
// c => 3
// d => null
// e => 5

函数参数默认值存在暂时性死区,未初始化赋值的参数值无法作为其他参数的默认值。

function f(x, y = x) {
    console.log(x, y);
}
f(1);

// x => 1
// y => 1

function f(x = y, y) {
    console.log(x, y);
}
f(undefined, 1);

// Error: Cannot access 'y' before initialization  (暂时性死区)

箭头函数

箭头函数是一种更加简洁的函数书写方式。

原始写法

const fun = function(num) {
    return num;
}

箭头函数

const fun = (num) => {
    return num;
}
fun(3)

// 3

如果参数只有一个,可以省略 ( )

const fun = num => {
    return num;
}
fun(3)

// 3

如果箭头函数只有一条返回语句,可以省略 { }return

const fun = num => num
fun(3)

// 3

如果返回值是一个对象时,省略后就会认为成函数体,此时会语法报错,我们只需要将返回的对象用( )包裹起来

// 省略前
const obj = (a, b) => {
    return {
        a: a,
        b: b
    }
}
// 省略后  SyntaxError
const obj = (a, b) => {
    a: a,
    b: b
}
// 把返回值用
const obj = (a, b) => ({
    a: a,
    b: b
})

箭头函数没有thisargumentnew.target

在箭头函数中,thisargumentnew.target分别对应的是箭头函数外层的thisargumentnew.target

const fun = () => {
    console.log(this)
}
fun()

// Window
const obj = {
    fun: function() {
        const func = () => {
            console.log(this);
        }
        func(4, 5, 6)
    }
};
obj.fun(1, 2, 3)

// fun

箭头函数没有原型
箭头函数没有原型,占用空间非常小,不能当成构造函数来使用。

const fun = () => true
console.log(fun.prototype)

// undefined
发布了33 篇原创文章 · 获赞 24 · 访问量 5508

猜你喜欢

转载自blog.csdn.net/qq_39157944/article/details/104914169