箭头,普通函数

155 阅读1分钟
普通函数
function fn(str){
let msg=str+'hello'
  return msg
  }
  let a=fn('张三');
  console.log(a);//张三hello
  
  箭头函数
  如果有多段表达式,需要使用{},并且return
  箭头函数只有一个参数,括号()可以省略
  let fn=str=>str+'hello';
  let a=fn('张三');
  console.log(a)//张三hello

普通函数可以构造函数,箭头函数不能

let f=new fn()
console.log(f)
  • 普通函数的this,谁调用就是谁的
  • 箭头函数没有自己的this,当中的this指的是上下文环境window
  • 箭头函数this不会被call或者apply修改

let obj1={
 name:'张三',
 fn:function(){
   console.log(this)
   }
 }
 let obj2={
   name:'李四'
   }
   obj1.fn.call(obj2);//普通函数this可以被call或者apply修改