在 JavaScript 中编写函数的 5 种方法
函数是用于执行单个操作的有组织的可重用代码块。
与 JavaScript 等许多编程语言一样,您可以通过多种方式添加和重复使用用于执行单个操作的代码。
这篇文章将教你七种编写 JavaScript 函数的方法:语法和一些示例。
我还会讨论何时可以有效地使用不同的类型,以及它们的优缺点。
目录
- 1 - 函数声明
- 2 - 函数表达式
- 3 - 简写方法定义
- 4 - 构造函数
- 5 - 箭头函数
1 - 函数声明
函数声明是 JavaScript 中定义函数的最常用方法。
要声明一个函数,您可以使用
function
关键字,后跟必需的函数名称、括号中的参数列表以及一对花括号来编写函数代码。
function nameOfTheFunction(param1, param2, ...){
console.log("Something")
// line1
...
}
例子
function isPositive(number){
return number > 0;
}
函数在当前执行范围内isPositive()
定义一个变量,isPositive
其标识符等于函数名。这意味着该变量isPositive
保存的是函数对象。
函数提升
函数声明最重要的特性之一是提升机制。它允许在同一作用域内,在声明之前使用该函数。
例子
multiplyNumbers(5,5)
function multiplyNumbers(a, b){
return a * b;
}
请注意,要执行已声明的函数,您需要调用它。如您所见,您只需编写函数名称,并在必要时在括号中包含参数即可。
2 - 函数表达式
函数表达式与函数声明的语法非常相似。
使用
var
、const
、 或let
关键字,后跟函数名称和影响符号(=
在 JavaScript 中),输入关键字 function,后跟括号中的参数和一对包含函数代码的大括号。
const functionName = function(param1, param2, ...){
//code
}
这是一个明显的例子:
const sum = function(a, b){
return a + b;
}
sum(5, 6); // => 11
如果您想在对象内编写方法,函数表达式非常有用。
const methods = {
sum: function(a, b){
return a + b;
},
substract: function(a, b){
return a - b;
}
}
methods.sum(5,6); // => 11
methods.substract(5,6); // => -1
与允许提升的函数声明相反,如果尚未定义函数,则无法调用该函数。
使用函数表达式的主要优点之一是易于调试。当程序遇到错误时,堆栈跟踪将包含该函数的名称。
3 - 速记函数
ES2015引入了简写语法,它与 getter、setter 语法非常相似。
const obj = {
items:[],
get(index){
return this.items[index];
},
set(...elements){
this.items.push(...elements)
}
}
items.add("foo", "bar");
items.get(1) // => "bar"
您可以使用函数名称来定义它们,后跟一对括号中的参数列表,
()
再跟一对分隔主体语句的花括号。
这种函数语法在处理对象时非常常见。你可以像这样调用该函数:
object.functionName(...parameters)
。
优点
- 更短的语法更易于阅读;
- 命名函数被创建,与函数表达式相反;
4 - 构造函数
在 JavaScript 中,构造函数是用于创建对象的函数。
要创建构造函数,请使用关键字 function,后跟函数名称(按照惯例始终采用驼峰式),后跟一对可以添加参数的括号,后跟一对描述代码逻辑的花括号。
例子
function shoes(size, mark){
this.size = size;
this.mark = mark;
};
let yeezy = new shoes(37, adidas);
console.log(yeezy.size); => 37
console.log(yeezy.mark); => 'adidas'
这里要注意的最重要的事情之一是this
and的用法new
。这里this
指的是创建object
this 时。object
function vegetal(){
this.type = "vegetal";
};
let tomato = new vegetal();
console.log(tomato.type); => "vegetal"
要从构造函数创建对象,我们使用new
关键字。
优点
- 可用于创建多个可在不改变父级的情况下进行变异的对象。在这种情况下,它比对象表达式更有效。
例子
let vegetal = {
this.type = "vegetal";
};
let tomato = vegetal();
tomato.type = "Fruit";
console.log(tomato.type); //=> "Fruit"
- 如果您想向从构造函数派生的对象添加属性,您可以轻松地做到这一点。
例子
function vegetal(){
this.type = "vegetal";
}
let tomato = new vegetal();
let orange = new vegetal();
tomato.type = "Fruit";
orange.juice = true;
console.log(tomato.type); //=> "Fruit"
console.log(orange.juice); //=> true
console.log(vegetal.type, vegetal.juice); // => undefined, undefined
- 如果您想向构造函数添加新属性,只需使用
Object.prototype.property
。
例子
function vegetal(){
this.type = "vegetal";
}
let tomato = new vegetal();
let orange = new vegetal();
console.log(tomato.type, orange.type); //=> vegetal, vegetal
vegetal.prototype.isHealthy = true;
console.log(tomato.isHealthy, orange.isHealthy); //=> true, true
5 - 箭头函数
数组函数是 ES6 中最常用的功能之一。它允许开发人员以比函数声明更简洁的方式创建函数。
let sum = (a,b) => a+b;
let sum = function (a,b){
return a + b;
};
function person(){
this.name = "John";
showName = () => {
console.log(this.name);
}
}
let someone = new person()
现在,需要注意的是:this
箭头函数的关键字有点复杂。
常规函数的this
关键字代表调用该函数的对象。
例如,它可以是窗口、文档或按钮。
但是,使用箭头函数时,this
关键字始终代表定义箭头函数的对象。
好吧,听起来有点复杂。让我们看一些在浏览器控制台中尝试的例子:
// Declaring a normal function
function greetings() {
console.log("Hello " + this);
};
greetings(); // => "Hello [object Window]"
现在,让我们使用箭头函数。
const greetings = () => console.log("Hello " + this);
greetings(); // => "Hello [object Window]"
结果是一样的吧……这很正常。this
这里代表 Object Window,因为该函数是在 Object Window 对象作用域内定义的。
让我们用我们自己的对象创建一个箭头函数。
const greetings = {
greetUser: null,
hello: function () {
this.greetUser = () => { console.log(this) };
}
};
greetings.hello(); // To initialize greetings.greetUser with an arrow function
greetings.greetUser(); // => Object { greetUser: greetUser(), hello: hello() }
优点
- 减少大量代码,提高可读性。实际上,箭头函数用于回调时非常有效。
- 具有上下文
this
缺点
- 避免对事件处理程序、对象方法原型方法或使用
arguments
对象的函数使用箭头函数
结论
在本文中,我们学习了在 JavaScript 中编写函数的 5 种方法。JavaScript 中还有更多编写函数的方法,但为了简单起见,我决定只介绍您在学习过程中会遇到的最常见函数。
如果您想了解更多信息,可以参考以下资源:
每篇文章都可以变得更好,所以欢迎在评论区提出您的建议或问题。😉
文章来源:https://dev.to/koladev/5-ways-to-write-functions-in-javascript-17d5