this指向的几种情况
1. this出现在全局函数中,永远指向window
var Car = function() {
console.log(this); // window
console.log(this.Car == window.Car,Car == window.Car); // true true
}
Car();
原因:Car作为全局函数,直接调用时,函数的this指向window。即Car == window.Car === this.Car
2. this出现在严格模式中 永远不会指向window
函数中使用es5的严格模式 ‘use strict’,this为undefined
var Car = function() {
'use strict'
console.log(this); // undefined
}
Car();
3. 函数为对象的一个属性时,在此函数内部this指向这个对象
var car = {
name:'wd',
run() {
console.log(this); // {name: "wd", run: ƒ}
}
}
4. this在构造函数中,指向构造函数新创建的对象
var Car = function(name) {
this.name = name;
console.log(this); // 输出:Car {name: "wd"}
// 输出:Car {name: "wt"}
}
// 构造函数新创建的对象
var myCar_1 = new Car('wd');
var myCar_2 = new Car('wt');
5. 标签元素被绑定事件处理函数时,this指向的是被点击的标签元素
var btn = document.querySelector('button');
btn.onclick = function() {
console.log(this); // <button>this</button>
}
6. this出现在箭头函数中,指向是父级程序的this指向,如果没有父级程序或者父级程序没有this那么箭头函数的this执向是window。
var title = 'hello,wd'
const arrow = () => {
let title = 'hello,wt'
console.log(this.title) // 输出:hello,wd
}
7. this出现在事件绑定函数中,默认指向 window,但会随着函数绑定环境而变
<button id="button" onclick="handlerClick()">点我</button>
<script type="text/javascript">
var title = 'hello,wd'
function handlerClick() {
console.log(this.title) // 输出:hello,wd
}
let obj = {
title: 'hello,wt',
handlerClick() {
console.log(this.title) // 输出 hello,wt'
}
}
document.getElementById('button').onclick = obj.handlerClick
</script>
8. this出现在setTimeout中,普通函数 this 指向 window,而箭头函数的 this 指向上一层环境
a. 普通函数 this 指向 window
// 在普通函数中
var title = 'hello,wd'
let obj = {
title: 'hello,wt',
getOut() {
setTimeout(function() {
console.log(this.title)
})
}
}
obj.getOut() // 输出:hello,wd
b. 箭头函数的 this 指向上一层环境
// 在箭头函数中
var title = 'hello,wd'
let obj = {
title: 'hello,wt',
getOut() {
setTimeout(() => {
console.log(this.title)
})
}
}
obj.getOut() // 输出:hello,wt
改变this指向的几种方法
call、apply、bind 三者共同点:第一个参数都为改变this的指针。若第一参数为null/undefined,this默认指向window。
1. call(无数个参数)
第一个参数:改变this指向
第二个参数:实参
使用之后会自动执行该函数
function fn(a,b,c){
console.log(this,a*b*c); // this指向window
}
fn(); // 输出: Window {...} NaN
fn.call(document,1,2,3);//call改变之后this指向document
// 输出: #document 6 1,2,3是实参 结果相乘为6
// document指当前整个文档页面
2. apply(两个参数)
第一个参数:改变this指向
第二个参数:数组(里面为实参)
使用时候会自动执行函数
function fn(a,b,c){
console.log(this,a*b*c);
}
fn(); // 输出: Window {...} NaN
fn.apply(document,[1,2,3]); // 输出: #document 6 1,2,3是实参 结果相乘为6
3. bind(无数个参数)
第一个参数:改变this指向
第二个参数之后:实参
返回值为一个新的函数
使用的时候需要手动调用下返回 的新函数(不会自动执行)
function fn(a,b,c){
console.log(this,a+b+c); //window
}
let a = fn.bind('wd',1,2,3); //手动调用
a(document) // 输出:String {'wd'} 6
4. 在react中,改变this指向也可以使用箭头函数
hanclerClick(){
console.log('点击点击')
}
<button onClick={()=>this.run()>点击</button>
call、apply与bind区别:
call 和 apply 可以自动执行,bind不会自动执行,需要手动调用。
call 和 bind 都有无数个参数,apply只有两个参数,而且第二个参数为数组。