// 函数声明
function testFunction() {
return 'This is a test function';
}
// 函数表达式
const testFuncExpression = function() {
return 'This is a test function expression';
};
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