函数基础

1.函数声明

// 注意:可以在函数声明前调用
console.log(addNum(11, 22));
function addNum(a, b) {
  return a + b;
};
console.log(addNum(2, 4));

2.函数表达式

// 注意:不可以声明前调用
// console.log(add(10, 20));  err(add is not a function)
var add= function(num1, num2) {
  return num1+ num2;
}
console.log(add(10, 20));

3.构造函数

// 注意:
// 3.1通过函数声明的方式定义函数
// 3.2构造函数名称首字母大写
// 3.3构造函数内部使用this关键字初始化变量
// 3.4使用构造函数时,需要使用new关键字

function Person(name, age) {
  // 初始化变量
  this.name = name;
  this.age = age;
};
// 可以通过prototype添加对应方法
Person.prototype.info = function() {
  console.log("hello this is" + this.name + "this age" + this.age)
};

// 使用,使用new关键字
const xm = new Person("XiaoMing", 32);

// 可以通过xm.name获取name;xm.age获取age;xm.info()获取方法
console.log(xm.name + xm.age + xm.info());

4.匿名函数(没有函数名,自己调用自己,立即执行)

(function(num1, num2) {
  console.log(num1 + num2);
})(10, 20);

5.箭头函数

详情看这个:https://www.cnblogs.com/ranyonsue/p/11989281.html

// 5.1没有function名字

// 普通函数写法
const sum = function(a, b) {
  return a + b;
};

// 箭头函数一般写法
const sum = (a, b) => {
  return a + b;
};

// 箭头函数只有一个参数时,定义时可以不加小括号
const stus = infos => {
 return infos.name;
};

// 箭头函数只有一行操作代码时,可以不加大括号,不用return
const sum = (a, b) => a + b;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容