前言
记录this指向的学习
前端面试基础-面向对象中已总结this的几种情况,现在进行扩展
1 obj.fun()
this -> .(点) 前的 obj对象
var obj = {
name: '老王',
fun:function(){ console.log(this.name) }
}
obj.fun(); // 老王
2 new构造函数()
this -> new正在创建的新对象
function Obj(name) {
this.name = name;
this.fun = function () {console.log(this.name)}
}
var obj = new Obj('老王')
obj.fun(); // 老王
3 构造函数.prototype.fun=function(){}。
this -> 将来调用这个fun共有函数的 .(点) 前的某个子对象,因为将来原型对象中的方法,都是”子对象.fun()”方式调用。
function Obj(name) {
this.name = name;
}
Obj.prototype.fun = function () {console.log(this.name)}
var obj = new Obj('老王')
obj.fun(); // 老王
4 匿名函数自调和回调函数中的
this -> window
严格模式(usestrict)下,this->undefined因为这类函数调用时,前边即没有.,也没有new!
"use strict";
(function () {
console.log(this) // 'use strict' -> undefined 非'use strict' this -> window
})(); // 匿名函数自调
var arr = [1]
arr.forEach(function () { // 回调函数
console.log(this) // 'use strict' -> undefined 非'use strict' this -> window
});
5 箭头函数中的this
指向 当前函数之外最近的作用域中的this
- 几乎所有匿名函数都可用箭头函数简化
- 箭头函数是对大多数匿名函数的简写
- 箭头函数只让this指向外部作用域的this,而箭头函数内的局部变量,依然只能在箭头函数内使用。出了箭头函数不能用! 所以,箭头函数依然是作用域!只不过影响this而已!不影响局部变量。箭头函数底层相当于.bind(),永久绑定外部this
var obj = {
num: 0,
arr: ['1', '2', '3'],
fun: function () {
this.arr.forEach(function (n) {
console.log(this.num + n) // forEach回调函数 this -> window 此处 this.num 是undefined
})
}
// 箭头函数改变回调函数的 *this指向 最近的外部this *
// fun: function () {
// this.arr.forEach((n) => {
// console.log(this.num + n) // 正常输出 01,02,03
// })
// }
// 箭头函数的底层原理是用 *bind绑定*
// fun: function () {
// this.arr.forEach(function (n) {
// console.log(this.num + n) // forEach回调函数 this -> window 此处 this.num 是undefined
// }.bind(this))
// }
}
obj.fun()
6 改绑this (bind/apply/call)
- 可用call,临时替换一次函数中的this
- 1). 立刻调用一次 .(点) 前的函数
- 2). 自动将 .(点) 前的函数中的this替换为指定的新对象
- 3). 还能向要调用的函数中传实参值
- 可用apply(要拆散数组再传参),临时替换一次函数中的this
- 可用bind,永久替换函数中的this,call无法替换箭头函数里面的this
function addsum(base, bonus1, bonus2) {
console.log(`${this.ename}的总工资是:${base + bonus1 + bonus2}`)
}
var lw = { ename: '老王' }
addsum.call(lw, 5000,2000,1000) // 老王的总工资是:8000
// apply 的使用
var arr = [5000,2000,1000]
addsum.apply(lw, arr) // 老王的总工资是:8000
// bind永久绑定this
var addsum2 = addsum.bind(lw)
var addsum3 = addsum.bind(ll,5000)
addsum2(5000,2000,1000) // 老王的总工资是:8000
addsum3(1000,1000) // 老李的总工资是:7000
7 DOM事件中的this
this -> 触发当前事件的 .(点) 前的 DOM元素对象
此处若希望this指向DOM元素,不可随意改 箭头函数 ,一改 this -> window
var btn = document.getElementsByTagName('button')[0]
btn.onclick = function () { console.log('button', this) }
btn.addEventListener('click', function () { console.log('button', this) })
最后
以上的方式总结只是自己学习总结,有其他方式欢迎各位大佬评论
渣渣一个,欢迎各路大神多多指正,不求赞,只求监督指正( ̄. ̄)
有关该文章经常被面试问到的可以帮忙留下言,小弟也能补充完善完善一起交流学习,感谢各位大佬(~ ̄▽ ̄)~