1. 匿名函数
- 一个函数只使用一次时,都必须用匿名函数
(function(形参列表){
})(实参列表); // 标准写法,分号最好写上
+function(){}() // 这两种写法也可以
!function(){}()
- 函数提升
say(); // 报错 匿名函数没有函数提升
let say = function () {
console.log('hello');
};
show(); // 正常运行 具名函数有函数提升
function show() {
console.log('world');
};
2. 特殊参数
- 每个函数都有一个Arguments对象实例arguments,它引用着函数的实参
function show() {
console.log(arguments) // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
console.log(arguments.length) // 5
}
show(1, 2, 3, 4, 5)
- 剩余运算
function show(...args) {
console.log(args) // [ 1, 2, 3 ]
}
show(1, 2, 3)
3. 箭头函数
- 专门对函数定义的简写语法
// 普通函数
arr.sort(function(a, b){ return a - b; });
// 箭头函数
arr.sort((a, b) => a - b);
a. 去掉function,在 () 和 {} 之间加 =>
b. 如果形参列表只有一个形参,可省略( )
c. 如果函数体只有一句话,可省略{ }
如果仅有的这一句话还是return,则必须省略return,且结尾的 ; 也要去掉
4. 改变this指针的几种方法
let Lesson = {
site: "学习",
lis: ['css', 'js', 'vue', 'react'],
show: function () {
console.log(this) // 类方法中的 this 指当前对象
return this.lis.map(function (val) {
console.log(this) // 普通函数中的 this 指window,如何改变 this 指向当前对象?
})
}
}
- 通过常量改变
show: function () {
const left = this // left 引用 this指针
return this.lis.map(function (val) {
console.log(left) // left 会向上查找
})
}
- 通过map的第二参数
show: function () {
return this.lis.map(function (val) {
console.log(this)
}, this) // 第二参数
}
- 箭头函数
show: function () {
return this.lis.map((val) => {
console.log(this) // 箭头函数内外 this 一致
})
}
- bind 函数
show: function () {
return this.lis.map(function () {
console.log(this)
}.bind(this))
}
5. call apply bind
- 三个函数的作用,都是用来重新定义 this 这个对象的
- 这三个函数的第一个参数都是 this 的指向对象,第二个参数 apply 传的是数组,另外2个一样是普通传参
- call 和 apply 函数调用后会立即执行,而bind不会,它返回的是一个函数,需要重新调用,也可以二次传参
let lisi = {
name: "李四"
};
let wangwu = {
name: "王五"
};
function User(web, url) {
console.log(web + url + this.name)
}
User.call(lisi, "百度", "www.baidu.com");
User.apply(wangwu, ["头条", "www.toutiao.com"]);
User.bind(lisi, "京东", "www.jd.com")();