箭头函数和普通函数的区别


箭头函数和普通函数的区别主要有以下四点:(1)语法简洁性,箭头函数比普通函数更为简洁;(2)this指向的不同;(3)有无arguements对象;(4)能不能用作构造函数


1、语法简洁性

直接看代码,相对于普通函数,箭头函数不用写function,有时候还可以省略{}和return,当只有一个参数时,()也可以省略。

//普通函数
function add(a,b){
     return a+b
}
//箭头函数
const add=(a,b)=>a+b

2、this指向不同

普通函数中,this是在函数被调用是确定的,它指向调用该函数的对象;而箭头函数的this是在函数定义是就确定了,它指向函数定义时所在的定义域,即箭头函数没有自己的this,它继承父级作用域的this。

(1)普通函数

  • this指向全局对象
    作为函数独立调用时,this 一般指向全局对象(在浏览器中是 window,在Node.js中是 global)
function func() {
 console.log(this); // window 或 global
}
func();
  • this指向调用它的对象
    当函数被对象调用时,this指向调用它的对象。
const obj = {
name:'dog',
 method: function() {
   console.log(this); // { name: 'dog', method: [Function: method] }
   console.log(this.name);//dog
 }
};
obj.method();
  • this指向参数
    使用 call 、 apply或者bind 方法调用时,this 指向 call 、 apply或bind 方法的第一个参数。
function foo(a,b) {
    console.log(this) //[Number: 1]
          
  }
 foo.call(1,2)
  • this指向实例化对象
    在构造函数里面的this指向实例化出来的对象
function Constructor() {
  this.value = 'Hello';
}
const instance = new Constructor();
console.log(instance.value); // Hello

(2)箭头函数

指向window、指向父级作用域的this
(1)this指向window
this只想父级作用域的this,当父级作用域为全局作用域时,this指向window,此时this.item为undefined。

const obj={
    name:"a",
    fun:()=>{
        console.log(this.name)//undefined
    }
}
obj.fun()

(2)箭头函数的this指向父级作用域的this

function foo() {
            console.log(this) // { a: 1, foo: [Function: foo] }
            var test = () => {
                console.log(this) // { a: 1, foo: [Function: foo] }
            }
            test()
 }
 var obj = {
        a: 1,
        foo: foo
    }
obj.foo()

(3)总结

  • 普通函数的this指向调用该函数的对象
    ① 独立调用时,指向全局对象(window或global)
    ② 被对象调用时,指向调用它的对象
    ③ 使用call、apply或bind方法调用时,指向他们的第一个参数
    ④ 在构造函数中使用时,指向实例化该构造函数的对象
  • 箭头函数的this指向该函数定义是所在的定义域
    ① 在全局作用域定义时,this指向window,此时this.item为undefined
    ② 在普通函数中定义时,this继承普通函数的this指向

3、有无arguements对象

(1)普通函数有arguements对象
在普通函数中,可以使用arguements对象访问函数的所有对象,它是一个类数组对象。

function fun(){
    console.log(arguments[0])//1
    console.log(arguments[1])//2
    console.log(arguments[2])//3
}
fun(1,2,3);

(2)箭头函数无arguements对象
箭头函数没有自己的 arguments 对象,但可以通过 rest 参数语法来获取所有参数。

function fun(){
    console.log(arguments[0])//报错!
}
fun(1,2,3);

4、是否能作为构造函数

(1)普通函数可以作为构造函数
普通函数可以用作构造函数,可以通过new关键字来创建实例化对象。

function Person(name){
    this.name=name
}
const p=new Person('dog')
console.log(p.name)//dog

(2)箭头函数不能作为构造函数

const Person=(name)=>{
    this.name=name
}
const p=new Person('hh')
console.log(p.name)//ERROR
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值