es6箭头函数有哪些特性-LMLPHP

本教程操作环境:windows7系统、ECMAScript 6版、Dell G3电脑。

ES6标准新增了一种新的函数:Arrow Function(箭头函数)。

为什么叫Arrow Function(箭头函数)?因为它的定义用的就是一个箭头:

x => x * x
登录后复制

上面的箭头函数相当于:

function (x) {    
return x * x;
}
登录后复制

箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ ... }和return都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }和return:

x => {
    if (x > 0) {
        return x * x;
    }
    else {
        return - x * x;
    }
}
登录后复制

如果参数不是一个,就需要用括号()括起来:

// 两个参数:
(x, y) => x * x + y * y

// 无参数:
() => 3.14

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

如果要返回一个对象,就要注意,如果是单表达式,这么写的话会报错:

// SyntaxError:
x => { foo: x }
登录后复制

因为和函数体的{ ... }有语法冲突,所以要改为:

// ok:
x => ({ foo: x })
登录后复制

es6箭头函数的特性

1、箭头函数没有arguments

let test1 = () => {
    console.log(arguments)
}
test1(123) // arguments is not defined
登录后复制

箭头函数找arguments对象只会找外层非箭头函数的函数,如果外层是一个非箭头函数的函数如果它也没有arguments对象也会中断返回,就不会在往外层去找

function test2(a, b, c){
    return () => {
    console.log(arguments) // [1]
    }
}
test2(1)()
登录后复制

2、箭头函数this值

箭头函数的this值,取决于函数外部非箭头函数的this值,如果上一层还是箭头函数,那就继续往上找,如果找不到那么this就是window对象

let person = {
    test: () => {
        console.log(this)
    },
    fn(){
        return () => {
            console.log(this)
        }
    }
}
person.test()  // window
person.fn()()  // person对象
登录后复制

箭头函数不能改变this指向

let person = {}
let test = () => console.log(this)
test.bind(person)()
test.call(person)
test.apply(person)
登录后复制

es6箭头函数有哪些特性-LMLPHP

在预编译的时候,this 就已确定。

3、箭头函数不能用new关键字声明

let test = () => {}
new test() // Uncaught TypeError: test is not a constructor
登录后复制

4、箭头函数没有原型prototype属性

JavaScript中所有的函数都有prototype属性吗,这个是错误的。

let test = () => {}
test.prototype // undefined
test.__proto__ === Function.prototype // true
登录后复制

箭头函数不能重复命名参数

// 箭头函数不能重复命名参数
let bbb = (b, b, b) => {
} 
// Uncaught SyntaxError: Duplicate parameter name not allowed in this context
let bb = function(b, b, b){
}
// es5 不会报错
登录后复制

【相关推荐:javascript视频教程web前端

以上就是es6箭头函数有哪些特性的详细内容,更多请关注Work网其它相关文章!

09-15 20:10