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

1. 语法定义

  • 普通函数:使用 function 关键字来定义,可以是函数声明或者函数表达式。
// 函数声明
function testFunction() {
    return 'This is a test function';
}

// 函数表达式
const testFuncExpression = function() {
    return 'This is a test function expression';
};
  • 箭头函数:使用箭头 => 来定义,语法更加简洁。

2. this 指向

  • 普通函数this 的指向在函数调用时动态确定,取决于函数的调用方式。
  • 箭头函数:它没有自己的 this,而是继承自外层函数的 this 值。

3. arguments 对象

  • 普通函数:函数内部可以使用 arguments 对象,它是一个类数组对象,包含了函数调用时的所有参数
function sum() {
    let total = 0;
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}
console.log(sum(1, 2, 3)); // 输出: 6
  • 箭头函数:没有自己的 arguments 对象,如果要访问参数,可以使用剩余参数语法
const sumArrow = (...args) => {
    let total = 0;
    for (let arg of args) {
        total += arg;
    }
    return total;
};
console.log(sumArrow(1, 2, 3)); // 输出: 6

4. 原型

  • 普通函数:有自己的 prototype 属性,可以使用 new 关键字创建实例对象。
  • 箭头函数:没有 prototype 属性,不能使用 new 关键字创建实例对象。
function Person(name) {
    this.name = name;
}
Person.prototype.sayHello = function() {
    console.log(`Hello, my name is ${this.name}`);
};
const person = new Person('John');
person.sayHello(); // 输出: Hello, my name is John

5. super 关键字

  • 普通函数:在类的方法中可以使用 super 关键字来调用父类的方法。
  • 箭头函数:不能使用 super 关键字。
class Parent {
    sayHello() {
        console.log('Hello from parent');
    }
}
class Child extends Parent {
    sayHello() {
        super.sayHello();
        console.log('Hello from child');
    }
}
const child = new Child();
child.sayHello(); 
// 输出:
// Hello from parent
// Hello from child

6. yield 关键字

  • 普通函数:可以使用 yield 关键字(在生成器函数中),用于暂停和恢复函数的执行。
function* generatorFunction() {
    yield 1;
    yield 2;
}
  • 箭头函数:不能使用 super 关键字。
const generator = (x) => x; // 错误,箭头函数不支持yield

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值