this关键字:表示当前对象(与使用场景有关)
this使用的几种场景
function fn1() {
console.log(this);
this.a = 10
}
let obj = {
a: 1,
b: 2,
fn: function () {
console.log('对象方法中的this', this);
}
}
<button>this</button>
setTimeout(() => {
console.log('定时器', this);
}, 1000);
let btn =document.querySelector('button')
btn.onclick=()=>{
console.log(this);
}
let fn2 =(function () {
console.log(this);
})()
改变this指向
- 改变this指向可以通过三种方式,分别是call,apply,bind
call
var obj = {
name: 'jack',
age: 23
}
function fn(a, b) {
this.name = a
this.age = b
console.log(this);
}
fn.call(obj, '小明', 20)
apply
var obj = {
name: 'jack',
age: 23
}
function fn(a, b) {
this.name = a
this.age = b
console.log(this);
}
fn.apply(obj, ['小明', 20])
bind 会返回一个新函数
var obj = {
name: 'jack',
age: 23
}
function fn(a, b) {
this.name = a
this.age = b
console.log(this);
}
var newFn = fn.bind(obj, '小明', 20)
newFn()
call、apply、bind 异同点
- call和bind传参方式相同
- call和apply传参方式不同
- call和apply不会返回一个新函数,bind会返回一个新的函数,通过调用这个函数才能实现相应的功能
箭头函数中的this问题
- 箭头函数中没有this,里面的this指向上下文(调用对象所在的对象)
构造函数中的this
- 指向被创建出来的对象
- new 关键字的作用,将构造函数中的this指向被创建出来的对象
总结