1. 箭头函数的两种形式
(1)无{…}和return
x =>x*x;
(2)有{…}和return
x=>{
if(x>0){
return x*x;
}else{
return -x*x;
}
}
2. 箭头函数的参数
(1) 无参数;eg: ( )=>3.14
(2)参数只有一个 ;eg:x=>x+x;
(3)参数不止一个,要用()将参数括起来;eg: (x,y)=>x+y
(4)可变参数;
(a,b,...reset)=>{
var i , sum = a + b ;
for( i = 0 ; i <= reset.length ; i++){
sum += reset[i];
}
return sum;
}
3. 箭头函数中的this
箭头函数内部的this是词法作用域(所谓的 词法( 代码 )作用域, 就是代码在编写过程中体现出来的作用范围. 代码一旦写好, 不用执行,
作用范围就已经确定好了. 这个就是所谓词法作用域),由上下文决定。
用call()或者apply()调用箭头函数时,无法对this进行绑定,即传入的第一个参数被忽略。
4. 注意:
当返回值时单表达式时
x => {foo:x} (错,此时的{…}与函数的{…}冲突)
x => ({foo:x})(对)
在 js 中词法作用域规则:
1. 函数允许访问函数外的数据.
2. 整个代码结构中只有函数可以限定作用域.
3. 作用规则首先使用提升规则分析
4. 如果当前作用规则中有名字了, 就不考虑外面的名字
例:
箭头函数:
getTodoById: (state, getters) => (id) => {
return state.todos.find(todo => todo.id === id)
}
相当于普通函数:
var getTodoById = function(state,getters){
return function(id){
return state.todos.find(function(todo){
return todo.id === id
})
}
}