javascript - 使用 "var that = this"了解 Javascript 作用域

标签 javascript

<分区>

假设我在一个对象中有以下属性方法:

  onReady: function FlashUpload_onReady()
  {
     Alfresco.util.Ajax.jsonGet({
       url: Alfresco.constants.PROXY_URI + "org/app/classification",
       successCallback: {
         fn: function (o) {
           var classButtonMenu = [],
               menuLabel, that = this;

           var selectButtonClick = function (p_sType, p_aArgs, p_oItem) {
               var sText = p_oItem.cfg.getProperty("text");
               that.classificationSelectButton.set("label", sText);
           };

           for (var i in o.json.items) {
             classButtonMenu.push({
               text: o.json.items[i].classification,
               value: o.json.items[i].filename,
               onClick: {fn: selectButtonClick}
             });
           }

           this.classificationSelectButton = new YAHOO.widget.Button({
             id: this.id + "-appClassification",
             type: "menu",
             label: classButtonMenu[0].text,
             name: "appClassification",
             menu: classButtonMenu,
             container: this.id + "-appClassificationSection-div"
           });
         },
         scope: this
       },
       failureMessage: "Failed to retrieve classifications!"
     });

我花了一些猜测才弄清楚,在 selectButtonClick 函数中,我需要引用 that 而不是 this 才能获得对 this.classificationSelectButton 的访问权限(否则出现 undefined),但我不确定为什么我不能使用 this。我最好的猜测是,在调用构造函数后,在 new YAHOO.widget.Button 中引用的整个对象中的任何属性都会以某种方式失去作用域。

有人可以解释一下为什么我必须使用 var that = this 来引用 classificationSelectButton 而不是仅仅调用 `this.classificationSelectButton' 吗?

最佳答案

最重要的是要理解函数对象没有固定的this——this的值会根据关于函数的调用方式。我们说一个函数是用一些特定的 this 值调用 -- this 值是在调用时确定的,而不是定义时。

  • 如果该函数被称为“原始”函数(例如,只需执行 someFunc()),this 将是全局对象 (window 在浏览器中)(如果函数在严格模式下运行,则为 undefined)。
  • 如果它作为对象的方法被调用,this 将是调用对象。
  • 如果您使用 call 调用一个函数或 apply , this 被指定为 callapply 的第一个参数。
  • 如果它作为事件监听器调用(如此处所示),this 将是作为事件目标的元素。
  • 如果使用new 作为构造函数调用,this 将是一个新创建的对象,其原型(prototype)设置为prototype 属性的构造函数。
  • 如果函数是 bind 的结果操作,该函数将永远永远将 this 设置为生成它的 bind 调用的第一个参数。 (这是“函数没有固定的 this”规则的唯一异常(exception)——bind 生成的函数实际上确实有一个不可变的 this.)

使用var that = this; 是一种在函数定义时(而不是函数执行时)存储this 值的方法timethis 可以是任何东西,具体取决于调用函数的方式)。这里的解决方案是将 this 的外部值存储在变量(传统上称为 thatself)中,该变量包含在新定义的函数,因为新定义的函数可以访问在其外部范围内定义的变量。

关于javascript - 使用 "var that = this"了解 Javascript 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12370851/

相关文章:

javascript - 表单未提交任何参数

javascript - 原型(prototype)对象中缺少实例方法

javascript - 将日期作为字符串写入 Odata 模型 0CALDAY?

javascript - 我的 Joomla 模板正在使用 JS 加载我的自定义 CSS。有没有办法将唯一的版本标签添加到我的自定义 CSS 中?即 : custom. css?20180101

javascript - 如何将 Cognito 托管的 UI 集成到 React 应用程序中?

javascript - 导出图像时出现 eslint 错误 - 首选默认导出

javascript - 在 promises 中正确地使用 setState 不更新状态

javascript - 如何使用 jQuery 函数作为 .ready() 和 .change()

javascript - 使用 jQuery 在页面上 float DIV

javascript - 如何将标量乘法应用于四元数