this的指向

  • this的指向已关闭评论
  • 112 次浏览
  • A+
所属分类:Web前端
摘要

调用函数,并改变this指向。调用函数,并改变this指向,传递的参数必须是数组。


一、this的指向分类

分类 this指向
普通函数 window
构造函数 实例对象,原型对象里面的方法也指向实例对象
对象方法 该方法所属对象。若对象中的方法为普通函数写法吗,则this指向该方法所属对象,若为箭头函数,则this指向为window
事件绑定函数 绑定事件对象
定时器 window
立即执行函数 window
箭头函数 外层作用域中的this(且this指向不可改变)

二、改变函数内部this指向

1.函数名称.call(this要指向的,传递的参数1,...)
  • 调用函数,并改变this指向。

    var obj = {     name: 'zs',     age: 18 } function fn (a, b) {     console.log(this)	// this指向obj这个对象     console.log(a + b)	// 6 } fn.call(obj, 1, 5) 
2.函数名.apply(this要指向的,[传递的参数1,...])
  • 调用函数,并改变this指向,传递的参数必须是数组。

    var arr = [1, 88, 0, 34, 171, 23] // 利用apply传递数组(伪数组),借助数学内置对象求数组最大值/最小值 var max = Math.max.apply(Math, arr) console.log(max)	// 171 var min = Math.min.apply(Math, arr) console.log(min)	// 0 
3.函数名.bind(this要指向的,传递的参数1,...)
  • 不调用函数,但改变this指向,调用需要fn.bind(...)( )。

    <button>按钮1</button> <button>按钮2</button> <button>按钮3</button> <script> 	// 获取所有的按钮元素     let btns = document.querySelectorAll('button')     for (let i = 0; i < btns.length; i++) {         btns[i].addEventListener('click', function () {             // 点击后禁用按钮             this.disabled = true             setTimeout(function () {                 // 2秒后解除禁用该按钮                 this.disable = false             }.bind(this), 2000)         })     } </script>