Code前端首页关于Code前端联系我们

一篇文章了解这个参考

terry 2年前 (2023-09-08) 阅读数 212 #Vue

这是指问题

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指向新对象
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:函数中指向的对象
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, '男')
 

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门