自学内容网 自学内容网

如何指定this的值

1. 函数调用时指定

call -- 接收一个参数列表

apply -- 接收一个参数数组

2. 创建时指定this的值

bind -- 返回一个函数  传参方式与call相同

箭头函数 -- 其this值取决于上级作用域中的this值

<script>
        // 如何指定this的值
        // 1. 调用时指定this
        // 2. 创建时指定this

        // 1. 调用时指定this
        function fun(num1, num2) {
            console.log(this)
            console.log(num1, num2)
        }
        const person = {
            name: 'hjy'
        }
        // 1.1 call
        fun.call(person, 1, 2)
        // 1.2 apply
        fun.apply(person, [3, 4])

        // 2.创建时指定this
        // 2.1 bind  返回一个函数
        const bindFun = fun.bind(person, 5) // 此处可传递多个参数 不一定是一个
        bindFun(6)
        // 2.2 箭头函数 
        const food = {
            name: '新疆炒米粉',
            eat() {
                console.log(this)  //为food 取决于调用的对象  
                setTimeout(() => {
                    console.log(this)  // 为food  取决于外部作用域的this值
                }, 1000)
                setTimeout(function () {
                    console.log(this)  // 为全局对象(window)
                }, 1000)
            }
        }
        food.eat()
    </script>


原文地址:https://blog.csdn.net/ggg21534/article/details/142856512

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!