1.this默认绑定--函数独立调用不与某个对象进行绑定
- eg1: 普通函数直接调用,不进行任何对象的关联
function func() {
// Window
console.log(this);
}
func()
- eg2: 将函数作为参数传入另外一个函数
function foo() {
// window
console.log(this);
}
function func(bar) {
bar()
}
func(foo)
2.隐式绑定--通过对象调用
- eg1: 通过对象调用函数
let obj = {
name: 'coderwhh',
sayThis: function() {
// obj
console.log(this);
}
}
obj.sayThis()
- eg2: 隐式丢失(此案例将obj的foo方法赋值给bar,然后调用bar方法,相当于普通函数的直接调用,所以this依然是指向window的)
function foo() {
// Window
console.log(this);
}
let obj = {
name: "coderwhh",
foo: foo
}
// 将obj的foo赋值给bar
var bar = obj.foo;
bar();
3.显示绑定
-
- call、apply实现
function func() {
// coderwhh
console.log(this.name);
}
let obj = {name: 'coderwhh'}
func.call(obj)
func.apply(obj)
-
- bind实现
function func() {
// coderwhh
console.log(this.name);
}
let obj = {name: 'coderwhh'}
func.bind(obj)()
**call、apply、bind:**传入的第一个参数为即将绑定的对象,若传入为null或者undefined则忽略这个显示
- 3. 内置函数 (1)setTimeout: setTimeout中会传入一个函数,这个函数中的this通常是window
setTimeout(function() {
// window
console.log(this);
}, 1000);
(2)数组的forEach
- 4. new绑定
function Super(name, age) {
// Super {}
console.log(this);
this.name = name
this.age = age
}
let son = new Super('coderwhh', 18)
优先级: new > 显示绑定 > 隐式绑定 > 默认绑定
4.ES6箭头函数
箭头函数没有自己的this,默认指向在定义它时所处在的宿主对象
let obj = {
name: 'coderwhh',
sayThis: function() {
// {name: "coderwhh", sayThis: ƒ}
console.log(this);
setTimeout(() => {
// {name: "coderwhh", sayThis: ƒ}
console.log(this);
}, 1000)
setTimeout(function () {
// Window
console.log(this);
}, 1000)
}
}
obj.sayThis()