【JavaScript】this 指向由入门到精通
this 的概念
this 在JavaScript 及其其他面向对象的编程语言中,存在的目的是为了提供一种在对象方法中引用当前对象的方式。
它为方法提供了对当前实例的引用,使得方法能够访问或者修改实例的成员变量。
注意点:
- this 的绑定和定位的位置(编写的位置) 没有关系
- this 的绑定和调用方式以及调用的位置有关系
- this 是在运行时被绑定的
this 绑定规则
this 的绑定规则根据函数的调用方式分为四种主要规则。
默认绑定(Default Binding)
当函数在非严格模式下独立调用时,this默认绑定到全局对象(在浏览器中是window对象,在Node,js中是globaly对象)。
如果在严格模式下,this会被绑定为undefined。
开启严格模式:
脚本开启: ‘use strict’
函数内部开启:‘use strict’
注意:'use strict’写在代码顶端
隐式绑定(Implicit Binding)
当函数作为对象的方法被调用时,this 绑定到该对象。
此时,this的值就是调用方法的对象。
显式绑定(Explicit Binding)
通过 call 、apply或bind方法,可以显式地指定 this的绑定对象。
call 和 apply 会立即调用函数并传递this,而bind会返回一个新的函数并绑定指定的this。
new绑定(New Binding)
当通过new关键字调用构造函数时,this绑定到新创建的对象实例。
这个新对象由构造函数创建,并作为 this 的绑定对象。
除此之外还有箭头函数:
- 之所以设计箭头函数,仅仅是为了实现⼀种简洁的函数定义语法,⽆需考虑与函数(对象)相关的东⻄,所以箭头函数没有原型,即没有 prototype 属性,也没有相关的 super、new.target、this ,没有 arguments 对象 等。
- 箭头函数没有⾃⼰的 arguments 对象,所以⽆法通过它获取参数。如果要获取,可以⽤ rest 参数代替:let arguments = (…args) => args;。与 this、 super、new.target ⼀样,arguments 的值由最近外部作用域的非箭头函数决定:
- 不能通过 new 关键字调⽤:JS 的函数有两个内部⽅法:[[Call]] 和 [[Construct]]。当通过 new 调⽤普通函数时,执⾏ [[Construct]] ⽅法,创建⼀个实例对象,然后再执⾏函数体,将 this 绑定到实例上。当直接调⽤的时候,执⾏ [[Call]] ⽅法,直接执⾏函数体。⽽由于箭头函数并没有 [[Construct]] ⽅法,不能被⽤作构造函数,如果通过 new 的⽅式调⽤,会报错。
规则优先级
默认规则 < 隐式绑定 < 显示绑定
new绑定优先级高于隐式绑定
new绑定优先级高于bind
new绑定和 call、apply 是不允许同时使用的,所以不存在谁的优先级更高
// 如何确认this的值
// 1.全局执行环境
// 严格模式,非严格模式:全局对象(window)
// 2.函数内部
// 2.1 直接调用
// 严格模式下:undefined
// 非严格模式:全局对象(window)
// 2.2 对象方法调用
// 严格模式,非严格模式:调用者
// 3. 使用 new 方法调用构造函数,构造函数内的 this 会绑定到新创建的对象上。
// 4. 箭头函数,this 指向由外层(函数或者全局)作用域决定。
// 5. apply / bind / call 方法调用,函数体内的 this 绑定到指定参数的对象上。// ------------- 1.全局执行环境 -------------// 严格模式,非严格模式 全局对象(window)// 'use strict'// console.log(this)// ------------- 2.函数内部 -------------// 2.1 直接调用-非严格模式// function func() {// console.log(this) // window// }// func()// 2.1 直接调用-严格模式// function func() {// 'use strict'// console.log(this) // undefined// }// func()// 2.2 对象方法调用const food = {name: '猪脚饭',eat() {'use strict'console.log(this)}}// 非严格模式,严格模式food.eat() // 调用者
DOM 绑定事件中的 this
dom 元素绑定事件时,事件处理函数里面的 this 指向绑定了事件的元素。
此时和 target 不同,target 指向触发事件的元素。
<ul id="color-list"><li>red</li><li>yellow</li><li>blue</li><li>black</li><li>white</li>
</ul>
<script>let colorList = document.getElementById('color-list')colorList.addEventListener('click', function (e) {console.log('this:', this)console.log('target', e.target)console.log('srcElement:', e.srcElement)})
</script>
有些时候我们会遇到一些困扰,比如在 div 节点的事件函数内部,有一个局部的 callback 方法,该方法被作为普通函数调用时, callback 内部的 this 是指向全局对象 window 的。
<div id="div1">我是一个 div</div>
<script>window.id = 'window'document.getElementById('div1').onclick = function () {console.log(this.id) // div1const callback = function () {console.log(this.id)}callback() // window}
</script>
可以用一个变量保存 div 节点。
<div id="div1">我是一个 div</div>
<script>window.id = 'window'document.getElementById('div1').onclick = function () {console.log(this.id) // div1const that = thisconst callback = function () {console.log(that.id)}callback() // div1}
</script>
指定 this
call
通常是为函数(方法)指定 this 指向(其他对象)。
call 方法可以改变 this 的指向,指定 this 指向对象 obj,然后在对象 obj 的作用域中运行函数。
call 方法的参数,应该是对象 obj,如果参数为空或 null,undefind,则默认传参全局对象。
如果 call 传参不是以上类型,则转换为对应的包装对象,然后传入方法。
let obj = {}
console.log(obj.hasOwnProperty('toString')) // false 查看本身是否有某方法
console.log(obj.toString()) // [object Object] 调用toString方法 是继承来的方法
// 重写hasOwnProperty方法
// obj.hasOwnProperty = function () {
// return 'aaa'
// }
// console.log(obj.hasOwnProperty('toString')) // aaa// 可以使用 call 调用原生的方法
console.log(Object.prototype.hasOwnProperty.call(obj, 'toString')) // false
apply
可以通过 apply 方法,利用 Array 构造函数将数组的空元素变成 undefined。
let a = ['1', , '2']
Array.apply(null, a).forEach((e, i) => {console.log(e, i) // 1 0 undefined 1 2 2
})
配合数组对象的 slice 方法,可以将一个类数组的对象(比如 arguments 对象)转成真正的数组。
Array.prototype.slice.apply({0: 1, length: 1}) // [1]
Array.prototype.slice.apply({0: 1}) // []
console.log(Array.prototype.slice.apply({0: 1, length: 2})) // [1, undefined]
console.log(Array.prototype.slice.apply({length: 2})) // [undefined, undefined]
这个方法起作用的前提是,被处理的对象必须有length属性,以及相对应的数字键。
bind
let d = new Date()
d.getTime()
// let print = d.getTime
// this 的指向改变 导致报错 可以使用 bind 改变 this 的指向
// print() // this is not a Date object.let print = d.getTime.bind(d)
console.log(print()) // 1715074121540
bind 的一些注意点:
- 每一次返回一个新函数
- 结合回调函数使用
- 某些数组方法可以可以接收一个函数当做参数
- 结合 call
let slice = Function.prototype.call.bind(Array.prototype.slice)
// call 方法来源于 Function.prototype
// 这里是改写了 slice 方法
console.log(slice([1, 2, 3], 0, 1)) // 1function fn(){console.log(this.v)
}
let obj = {v:123
}
let func = Function.prototype.call.bind(Function.prototype.bind)
func(fn, obj)() // 123
可以通过两种方法指定this:
- 调用时指定:
- call方法
- apply方法
- 创建时指定:
- bind方法
- 箭头函数
/*** 如何指定this的值:* 1. 调用时指定this:* 2. 创建时指定this:* */// ------------- 1. 调用时指定this: -------------function func(numA, numB) {console.log(this)console.log(numA, numB)}const person = {name: 'username'}// 1.1 call:挨个传入参数// func.call(person, 1, 2) // this 为 {name: 'username'}// 1.2 apply:以数组的方式传入参数// func.apply(person, [3, 4]) // this 为 {name: 'username'}// ------------- 2. 创建时指定this: -------------// 2.1 bind方法// const bindFunc = func.bind(person, 666) // this 为 {name: 'username'} ,Func函数的参数可以依次传入// bindFunc(888) // numA 为 666,numB 为 888// 2.2 箭头函数const food = {name: '西兰花炒蛋',eat() {console.log(this) // food// 箭头会从自己作用域链的上一层继承thissetTimeout(() => {console.log(this) // food}, 1000);// setTimeout(function () {// console.log(this) // window// }, 1000)}}food.eat()
总结
如何确认this指向:
-
默认绑定:① 非严格模式:全局对象(window) ② 严格模式:undefined
-
隐式绑定:对象方法调用的this值:① 调用者
-
使用 new 方法调用构造函数,构造函数内的 this 会绑定到新创建的对象上。
-
箭头函数,this 指向由外层作用域决定。
-
apply / bind / call 方法调用,函数体内的 this 绑定到指定参数的对象上。
如何开启严格模式:
// 为整个脚本开启严格模式
'use strict'
function func() {// 为函数开启严格模式'use strict'
}
如何改变this
指向,有2类改变this
指向的方法,分别是:
- 调用函数时并传入具体的
this
call
:从第二个参数开始挨个传递参数apply
:在第二个参数以数组的形式传递参数
- 创建函数时绑定
this
?bind
:返回一个绑定了this
以及参数(可选)的新函数- 箭头函数:创建时会绑定上一级作用域中的
this
例题实战:
const foo = {bar: 10,fn: function () {console.log(this) console.log(this.bar) }
}
let fn1 = foo.fn
fn1() // window or global 和 undefined
foo.fn() // { bar: 10, fn: [Function: fn] } 和 10
面试题
// 1.
var name = "window"
var person = {name: 'person',sayName: function () {console.log(this.name)}
}
function sayName() {var sss = person.sayNamesss() // 独立调用 windowperson.sayName() // 隐式调用 person(person.sayName())() // 隐式调用 person(b = person.sayName)() // 独立调用 window
}
sayName()// 2.
var name = "window"
var person1 = {name: "person1",foo1: function () {console.log(this.name)},foo2: () => console.log(this.name),foo3: function () {return function () {console.log(this.name)}},foo4: function () {return () => console.log(this.name)}
}
var person2 = { name: "person2" }
person1.foo1() // 隐式绑定 person1
person1.foo1.call(person2) // 显示绑定优先级高于隐式绑定 person2person1.foo2() // 箭头函数没有 this 而外层是一个对象(不是作用域) 而非块级作用域 因此直接找到 window
person1.foo2.call(person2) // 本身就没有this 因此绑定不了this 因此也是 windowperson1.foo3()() // 独立调用 window
// 相当于
// const bar = person1.foo3()
// bar()
person1.foo3.call(person2)() // 和上面同理 因此也是 window
// 相当于
// const bar = person1.foo3().call(person2)
// bar()
person1.foo3().call(person2) // 这个是先拿到 foo3 的返回值函数,再调用这个函数并绑定this,因此是 person2person1.foo4()() // foo4 是普通函数 调用后this 为person1对象,相当于闭包 返回的箭头函数this 绑定了 foo4 中的 this,即指向 person1。
person1.foo4.call(person2)() // 箭头函数绑定的this为person1 外层作用域显示绑定了person2 所以最终为 person2
person1.foo4().call(person2) // 先调用foo4 返回的箭头函数无法绑定this 因此最初返回值箭头函数外部作用域的 person1// 3.
var name = "window"
function Person(name) {this.name = namethis.foo1 = function () {console.log(this.name)}this.foo2 = () => console.log(this.name)this.foo3 = function () {return function () {console.log(this.name)}}this.foo4 = function () {return () => console.log(this.name)}
}
var person1 = new Person("person1")
var person2 = new Person("person2")
person1.foo1() // 隐式绑定 person1
person1.foo1.call(person2) // 显示绑定优先级高于隐式绑定 person2person1.foo2() // 箭头函数没有 this 而外层是一个函数(作用域)new绑定 因此为 person1
person1.foo2.call(person2) // 箭头函数还是无法绑定 因此还是 person1person1.foo3()() // 独立调用 window
person1.foo3.call(person2)() // 和上面同理独立调用 因此也是 window
person1.foo3().call(person2) // 这个是先拿到 foo3 的返回值函数,再调用这个函数并绑定this,因此是 person2person1.foo4()() // 箭头函数不绑定this 使用外层作用域 person1
person1.foo4.call(person2)() // 箭头函数不绑定this 使用外层作用域的显示绑定 person2
person1.foo4().call(person2) // 箭头函数不绑定this 使用外层作用域 person1// 4. 对象没有作用域 外层普通函数有作用域
var name = "window"
function Person(name) {this.name = namethis.obj = {name: "obj",foo1: function () {console.log(this.name)},foo2: function () {return () => console.log(this.name)}}
}
var person1 = new Person("person1")
var person2 = new Person("person2")person1.obj.foo1()() // 独立调用 window
person1.obj.foo1.call(person2)() // 独立调用 window
person1.obj.foo1().call(person2) // 返回值普通函数的显示绑定 person2person1.obj.foo2()() // 闭包 箭头函数的this指向外层作用域 obj
person1.obj.foo2.call(person2)() // 闭包 箭头函数不绑定 外层作用域的显示绑定 person2
person1.obj.foo2().call(person2) // 闭包 箭头函数不绑定 外层作用域的隐式绑定 obj