在JavaScript中,function
(函数)是一种基本的构建块,用于创建可重用的代码段。函数可以接受输入参数,执行特定的任务,并且可能返回一个值。
function
关键字定义函数,后跟函数名、参数列表和函数体。return
语句返回一个值。function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice')); // 输出: Hello, Alice!
const add = (a, b) => a + b;
console.log(add(2, 3)); // 输出: 5
const person = {
firstName: 'John',
lastName: 'Doe',
getFullName: function() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.getFullName()); // 输出: John Doe
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};
const person1 = new Person('Jane', 'Smith');
console.log(person1.getFullName()); // 输出: Jane Smith
let
和const
)。确保变量在正确的作用域内声明和使用。this
关键字:在函数中使用this
时,要注意它的指向。箭头函数不绑定自己的this
,而是继承外层作用域的this
。如果你遇到了具体的JavaScript函数问题,可以提供更详细的信息,以便给出更具体的解决方案。
领取专属 10元无门槛券
手把手带您无忧上云