栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

'var that = this;'是什么?在JavaScript中意味着什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

'var that = this;'是什么?在JavaScript中意味着什么?

我将以一个插图开始这个答案:

var colours = ['red', 'green', 'blue'];document.getElementById('element').addEventListener('click', function() {    // this is a reference to the element clicked on    var that = this;    colours.forEach(function() {        // this is undefined        // that is a reference to the element clicked on    });});

我的回答最初是用jQuery演示的,只是略有不同:

$('#element').click(function(){    // this is a reference to the element clicked on    var that = this;    $('.elements').each(function(){        // this is a reference to the current element in the loop        // that is still a reference to the element clicked on    });});

由于

this
在通过调用新函数更改范围时会经常更改,因此无法使用原始值访问原始值。将其别名为
that
可以使您仍然访问的原始值
this

就个人而言,我不喜欢使用

that
as作为别名。它指的是什么几乎是不明显的,特别是如果函数长于几行。我 总是
使用更具描述性的别名。在上面的示例中,我可能会使用
clickedEl



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/390608.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号