js的function()写法
时间: 2023-08-15 22:07:08 浏览: 45
JavaScript中定义函数有两种方法:
1.函数声明:
```
function functionName(parameters) {
//函数体
return returnValue;
}
```
2.函数表达式:
```
var functionName = function(parameters) {
//函数体
return returnValue;
};
```
其中,parameters为函数的参数,可以有多个参数,用逗号分隔。returnValue为函数的返回值,可以省略不写。函数声明和函数表达式的区别在于函数声明会被提升到作用域的顶部,而函数表达式则不会。
相关问题
function 的写法
在 JavaScript 中,function 可以声明为函数声明或函数表达式两种方式。函数声明是以 function 关键字开头,后跟函数名和参数列表,函数体写在花括号内,如下所示:
```
function functionName(parameter1, parameter2, ...) {
// 函数体
}
```
函数表达式则是将一个匿名函数赋值给一个变量,并以该变量名调用函数,如下所示:
```
var functionName = function(parameter1, parameter2, ...) {
// 函数体
}
```
需要注意的是,在函数表达式中,变量名可以省略,直接将匿名函数赋值给一个对象属性或数组元素,或作为参数传递给其他函数,这称为匿名函数表达式,如下所示:
```
// 赋值给对象属性
var obj = {
func: function(parameter1, parameter2, ...) {
// 函数体
}
};
// 赋值给数组元素
var arr = [
function(parameter1, parameter2, ...) {
// 函数体
}
];
// 作为参数传递
someFunction(function(parameter1, parameter2, ...) {
// 函数体
});
```
js class写法
ES中的class写法是将对象原型的写法更加清晰,更像面向对象编程的语法。它是一种语法糖,实际上在底层仍然使用了ES5的原型继承机制。通过class关键字定义一个类,类中可以包含构造函数、方法等成员,并且可以使用extends关键字实现继承。
下面是一个使用ES6 class写法的例子:
```javascript
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p = new Point(1, 2);
console.log(p.toString());
```
与之对应的ES5写法如下:
```javascript
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
return '(' + this.x + ', ' + this.y + ')';
}
var p = new Point(1, 2);
console.log(p.toString());
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)