一、this的绑定规则
- 默认绑定
function foo() {
console.log(this)
}
foo();
- 隐式绑定
function foo() {
console.log(this)
}
var obj = {
name: "why",
foo: foo
}
obj.foo();
- 显示绑定
- new绑定
function foo() {
console.log("foo函数:", this);
}
new foo()
- 启示
- 在函数调用时,JavaScript会默认给this绑定一个值
- this的绑定和定义的位置没有关系
- this的绑定和调用方式以及调用的位置有关系
- this是在运行时被绑定的
二、apply/call/bind
function foo(name, age, height) {
console.log("foo:", this);
console.log("打印参数:", name, age, height);
}
foo("why", 18, 1.88)
- apply
- 第一个参数:绑定this
- 第二个参数:传入额外的实参,以数组的形式
foo.apply("apply", ["kobe", 30, 1.98])
- call
- 第一个参数:绑定this
- 参数列表:后续的参数以多参数的形式来传递,会作为实参
foo.call("call", "james", 25, 2.05)
- bind
var obj = { name: "why" }
var bar1 = foo.bind(obj)
var bar2 = foo.bind(obj, "kobe", 18, 1.88)
bar1()
bar2()
三、this绑定优先级
- 显示绑定的优先级高于隐式绑定
- new绑定优先级高于隐式绑定
- new/显式
- new不可以和apply/call一起使用
- new优先级高于bind
- bind优先级高于apply/call
四、箭头函数的使用
- 认识箭头函数
- ES6之后增加的一种编写函数的方法,并且它比函数表达式更简洁
- 箭头函数不会绑定this、arguments属性
- 箭头函数不能作为构造函数来使用
nums.forEach((item, index, arr) => {
})
- 箭头函数编写优化
nums.forEach(item => {})
nums.forEach(item => console.log(item))
- 如果函数执行体中只有返回一个对象,那么需要给这个对象加上括号
nums.forEach(item => ({name: "abc"}))
- 箭头函数this
- 箭头函数不绑定this对象
- this引用会从上层引用中找到对应的this
function request(url, callbackFn) {
var results = ["abc", "cba", "nba"]
callbackFn()
}
var obj = {
names: [],
network: function() {
var _this = this
request("/names", function(res) {
_this.names = [].concat(res)
})
request("/names", () => {
this.names = [].concat(res)
})
}
}
obj.network()
console.log(obj);