一文搞懂 this 指向

this 指向问题

1.对象中的方法

let names = 'lisi'
let obj = {
    names: 'zhangsan',
    fn: function() {
        console.log('I am', this.names)
    }
}
obj.fn()   //I am zhangsan
 

2.事件绑定

  • 行内绑定
<!-- this指向Window -->
<input type="button" value="clickFun按钮" onclick="clickFun()">

<script>
    function clickFun() {
        console.log('clickFun', this)
    }
</script>

<!-- this指向当前input Node -->
<input type="button" value="按钮" onclick="console.log(this)">

 
  • 动态绑定
<!-- this指向当前 input Node -->
<input type="button" value="按钮" id="btn">

<script>
    const btn = document.getElementById('btn')
    btn.onclick = function() {
        console.log(this)
    }
</script>

 
  • 事件监听
<!-- this指向当前 input Node -->
<input type="button" value="按钮" id="btn">

<script>
    const btn = document.getElementById('btn')
    btn.addEventListener('click', function() {
        console.log(this)
    })
</script>
 

3.构造函数

执行步骤:

  • 创建一个新的空对象
  • 将构造函数中的this指向本对象
  • 执行构造函数中的代码,为新对象添加属性
  • 返回新对象
// this指向新对象
function Pro() {
    this.x = '1'
    this.y = function() {}
}
const p = new Pro()
 

4.定时器

const obj = {
    fun: function() {
        console.log(this)
    }
}

setTimeout(obj.fun, 1000)      // this -> window
setTimeout('obj.fun()', 1000)    // this -> obj
 

5.函数对象的call()、apply() 方法

call 方法使用的语法规则:func.call(obj, arg1, arg2, …argN)

参数说明:
obj:函数内this要指向的对象
arg1, arg2…argN:参数列表,参数与参数之间使用一个逗号隔开

const lisi = {names: 'lisi'}
const zs = {names: 'zhangsan'}
function fn(age, gender) {
    console.log(this.names, age, gender)
}

// undefined 23
fn(23)
// 将 fn 函数中的this指向固定到对象zs上
fn.call(zs, 32, '男')
 
(0)
上一篇 2021年6月4日 上午11:19
下一篇 2021年6月4日 上午11:33

相关推荐

发表回复

登录后才能评论