前端开发this指向总结

218 阅读1分钟

JavaScript 中的 this指向

一,函数直接调用

1.非严格模式

function fn (){
	console.log(this)
}

fn() // window

2.严格模式

"use strict"
function fn (){
	console.log(this)
}

fn() // undefined

// 这里注意
// 如果fn是全局函数
window.fn() // winodw

二,作为对象的方法属性被调用

var obj = {
	fn(){
		console.log(this)
	}
}
obj.fn() // obj

三,函数作为构造函数执行时

funciont Fn(){
	this.name = 'obj'
	console.log(this)
}
var f = new Fn() // this 指向 f

四,箭头函数

箭头函数是es6中比较特殊的新语法他的this的判断规则只有一点,就是指向箭头函数所在的函数作用域中的this。

var fn = ()=>{
	console.log(this)
}
fn() // window
var obj = {
	fn: ()=>{
		console.log(this)
	},
	eat(){
		var fn = ()=>{
            console.log(this)
        }
		fn()
	}
}

obj.fn() // window
obj.eat() // obj

五,改变this指向

// 除了上面的基本判断this的方法,也可以刻意去改变this的指向
function fn(a,b){
	console.log(this,a ,b)
}
fn.call('这里的是新this', 'a', 'b') // '这里的是新this', 'a', 'b'
fn.apply('这里的是新this',['a', 'b']) // '这里的是新this', 'a', 'b'
// bind和上面的区别是不会立即执行改变this的函数
fn.bind('这里的是新this')('a', 'b') // '这里的是新this', 'a', 'b'

六,箭头函数不能被改变this

var fn = () => {
	console.log(this)
}
fn.call('123') // window