温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript中this指向问题实例讲解

发布时间:2021-08-30 16:51:05 来源:亿速云 阅读:120 作者:chen 栏目:开发技术

这篇文章主要讲解了“JavaScript中this指向问题实例讲解”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JavaScript中this指向问题实例讲解”吧!

总结

  • 全局环境 ➡️ window

  • 普通函数 ➡️ window 或 undefined

  • 构造函数 ➡️ 构造出来的实例

  • 箭头函数 ➡️ 定义时外层作用域中的 this

  • 对象的方法 ➡️ 该对象

  • call()、apply()、bind() ➡️ 第一个参数

全局环境

无论是否在严格模式下,this 均指向 window 对象。

console.log(this === window)  // true
// 严格模式
'use strict'
console.log(this === window)  // true

普通函数

  1. 正常模式

    • this 指向 window 对象

    • function test() {
        return this === window
      }
      
      console.log(test())  // true
  2. 严格模式

    • this 值为 undefined

    • // 严格模式
      'use strict'
      
      function test() {
        return this === undefined
      }
      
      console.log(test())  // true

构造函数

函数作为构造函数使用时,this 指向构造出来的实例。

function Test() {
  this.number = 1
}

let test1 = new Test()

console.log(test1.number)  // 1

箭头函数

函数为箭头函数时,this 指向函数定义时上一层作用域中的 this 值。

let test = () => {
  return this === window
}

console.log(test())  // true
let obj = {
  number: 1
}

function foo() {
  return () => {
    return this.number
  }
}

let test = foo.call(obj)

console.log(test())  // 1

对象的方法

函数作为对象的方法使用时,this 指向该对象。

let obj = {
  number: 1,
  getNumber() {
    return this.number
  }
}

console.log(obj.getNumber())  // 1

call()、apply()、bind()

  • 调用函数的 call()、apply() 方法时,该函数的 this 均指向传入的第一个参数。

  • 调用函数的 bind() 方法时,返回的新函数的 this 指向传入的第一个参数。

let obj = {
  number: 1
}

function test(num) {
  return this.number + num
}

console.log(test.call(obj, 1))  // 2

console.log(test.apply(obj, [2]))  // 3

let foo = test.bind(obj, 3)
console.log(foo())  // 4

感谢各位的阅读,以上就是“JavaScript中this指向问题实例讲解”的内容了,经过本文的学习后,相信大家对JavaScript中this指向问题实例讲解这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI