欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 如何指定this的值

如何指定this的值

2024/10/25 18:32:04 来源:https://blog.csdn.net/ggg21534/article/details/142856512  浏览:    关键词:如何指定this的值

1. 函数调用时指定

call -- 接收一个参数列表

apply -- 接收一个参数数组

2. 创建时指定this的值

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

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

<script>// 如何指定this的值// 1. 调用时指定this// 2. 创建时指定this// 1. 调用时指定thisfunction fun(num1, num2) {console.log(this)console.log(num1, num2)}const person = {name: 'hjy'}// 1.1 callfun.call(person, 1, 2)// 1.2 applyfun.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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com