this的相关介绍

本文详细解析了JavaScript中this关键字的概念及应用。介绍了this在不同环境下的指向规则,包括全局环境、函数调用、对象方法调用、构造函数、事件处理程序以及通过call和apply改变this指向的方法。

this的相关文章@TOC

this的详解

  1. this是当前对象的一个引用,用来承接上下文
  2. this不是固定不变的,随着执行环境的变化而变化
  3. 在函数体内部,指代当前函数的运行环境

this的指向

  1. 在全局环境中,this指向window(在nodejs环境中指向global)
console.log(this) // 此处的this指向的是window
  1. 局部环境
    2.1 严格模式下,函数中的this为undefined
    2.2 在全局作用域直接调用函数,隐式相当于window调用,所以指向window
    function fun () {
    	console.log(this) // 这里的this指向window
    }
    
    fun() // 这里相当于window.fun调用
    
    2.3 对象函数调用的时候,哪个对象调用就指向哪个对象
    const obj1 = {
    	a: 1,
    	fun1 () {
    		console.log(this)
    	},
    	obj2: {
    		fun2 () {
    			console.log(this)
    		}
    	}
    }
    obj1.fun1() // 此处的this指向obj1
    obj.obj2.fun2() // 此处的this指向obj2
    
    2.4 new一个构造函数的时候,构造函数中的this指向实例对象
    Function Fn () {
    	this.a = 1
    	console.log(this)
    }
    const obj = new Fn()
    
    2.5 在html事件中,this指向了接收事件的html元素
    <button onclick=	"this.style.display='none'">点击我通过this获取元素</button>
    
    2.6 通过显示绑定改变this的指向
    1. call-无数个参数

      • 第一个参数改变this指向
      • 之后每个参数为调用函数传进来的参数
      • 使用时会自动执行call函数
      1. 普通函数调用,第一个参数非undefined或者null,this指向第一个参数对象
      function fn (a, b, c) {
      	console.log(typeof this)
      	console.log(a)
      	console.log(b)
      	console.log(c)
      }
      fn.call(document, 1, 2, 3) // document
      fn.call(0, 1, 2, 3) // Number(0)-类型:对象
      fn.call(false, 1, 2, 3) // Boolean(false)-类型:对象
      fn.call('11', 1, 2, 3) // String('11')
      
      1. 普通函数调用,第一个参数为null或者undefined,this指向window
      function fn (a, b, c) {
      	console.log(this)
      	console.log(a)
      	console.log(b)
      	console.log(c)
      }
      fn.call(undefined, 1, 2, 3) // window 1 2 3
      fn.call(null, 1, 2, 3) // window 1 2 3
      
      1. 箭头函数调用call无效,直接忽略
  2. apply-两个参数
  • 参数1,改变this指向
  • 参数二,一个数组,为传递的参数
  • 使用时会自动执行apply函数
  • 除了传参不同其余和call相同
function fn (a, b, c) {
	console.log(this)
	console.log(a, b, c)
}
fn.apply(document, 1, 2, 3)
  1. bind-无数个参数
  • 参数1,改变this指向
  • 参数二及之后,函数传递进来的实参
  • 返回值为一个新的函数
  • 使用的时候需要手动再次调用一下返回的新函数
  • 和call、apply不一样,绑定bind不会自动执行
function fn (a, b, c) {
	console.log(this, a, b, c)
}

const newFn = fn.bind(document, 1, 2, 3)
newFn()
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值