0


前端经典面试题 | this相关问题

🖥️ 前端经典面试题专栏:this相关问题
🧑‍💼 个人简介:一个不甘平庸的平凡人🍬

✨ 个人主页:CoderHing的个人主页

🍀 格言: ☀️ 路漫漫其修远兮,吾将上下而求索☀️

👉 你的一键三连是我更新的最大动力❤️


一、回答点

this的指向 优先级 特殊this指向 ...

this的绑定规则有哪几种? 默认绑定、隐式绑定、显式绑定、new绑定

**默认绑定:**独⽴函数调⽤,函数没有被绑定到某个对象上进⾏调⽤

**隐式绑定:**通过某个对象发起的函数调⽤,在调⽤对象内部有⼀个对函数的引⽤

**显式绑定(apply/call/bind):**明确this指向的对象,第⼀个参数相同并要求传⼊⼀个对象

new绑定:

  1. 1) 创建⼀个全新对象
  2. 2 ) 新对象被执⾏prototype链接
  3. 3 ) 新对象绑定到函数调⽤的this
  4. 4 ) 如果函数没有返回其他对象,表达式会返回这个对象

二、深入回答

this的优先级

  1. ** new 绑定 > 显示绑定 > 隐式绑定 > 默认绑定**

特殊this指向

** 1 ) 箭头函数:**

** **箭头函数会根据其声明的地方来决定 this

  1. const fo = {
  2. fn:function(){
  3. setTimeout(function) {
  4. console.log(this)
  5. }
  6. }
  7. }
  8. console.log(fo.fn())
  9. // window
  1. this出现在定时器中的回调函数内,因此this指向window对象.如果需要this指向fo这个对象,可以用箭头函数
  1. const fo = {
  2. fn:function() {
  3. settimeout(()=>{
  4. console.log(this)
  5. })
  6. }
  7. }
  8. console.log(fo.fn())
  9. // {fn:f}

需要注意:箭头函数的this绑定是无法通过call apply bind方法修改.因为箭头函数没有构造函数constructor,所以也不可以使用new进行调用,不能作为构造函数.

** 2 ) 数组方法**

在属性arr的forEach回调函数中的this 指向什么?

  1. var obj = {
  2. arr:[1]
  3. }
  4. obj.arr.forEach(function(){
  5. console.log(this)
  6. })
  7. // forEach方法如下:
  8. Array.forEach(function(currentVal,index,arr),thisVal)
  9. // currentVal => 当前元素,必选
  10. // index => 索引值,可选
  11. // arr => 当前元素所属数组对象,可选
  12. // thisVal => 传递给函数的值 一般用this值,如果为空 会把undefined传递给this值.
  1. 输出:**全局对象**
  2. 这里可以看出来,只传递了一个值,第二个值未传递,默认为undefined,所以输出 **全局对象**
  3. **除了forEach方法外,还有其他的方法函数需要传递,可以查看Mdn文档.**

** 3 ) 立即执行函数**

立即执行函数 => 定义后立即调用的函数 为 立即执行函数

  1. var name = "coderhing"
  2. var obj = {
  3. name:"coder",
  4. sayHello:function(){
  5. console.log(this.name)
  6. },
  7. hello:function(){
  8. (function(ch) {
  9. ch()
  10. })(this.sayHello)
  11. }
  12. }
  13. obj.hello()
  14. // 输出 coderhing
  1. 输出为coderhing,是window.name的值.立即执行函数是匿名函数,可以直接调用,而不是通过属性访问(obj.fn)的形式来给它指定一个对象,所以它的this是确定的,就是默认的全局对象window

4 ) 定时器

setTimeout和setInterval中函数的this指向规则是一样的

  1. var name = "coderhing"
  2. var obj = {
  3. name:"coder",
  4. hello:function(){
  5. setTimeout(function() {
  6. console.log(this.name)
  7. })
  8. }
  9. }
  10. obj.hello()
  11. // 输出 coderhing

this.name是在obj.hello()被调用的,结果输出 window.name , 定时器 都是在全局作用域下实现的.

无论是setTimeout和setInterval里传入的函数,都会首先被交到全局对象手里.因此,函数中的this值 指向 window.

标签: 前端 html javascript

本文转载自: https://blog.csdn.net/coderHing/article/details/127586043
版权归原作者 coderHing 所有, 如有侵权,请联系我们删除。

“前端经典面试题 | this相关问题”的评论:

还没有评论