javascript - 无法通过 'this' 访问属性

标签 javascript scope this private

<分区>

在下面的代码片段中,我尝试从成员函数 shift() 中访问属性 offset。看起来,我无法通过这种方式访问​​它,因为 console.log 报告 Offset: NaN:

function shiftImg() {
  this.offset = 0;
  this.shift =
    function() {
      this.offset++;
      console.log("Offset: " + this.offset);
    };
}

productImg = new shiftImg;
window.setInterval(productImg.shift, 100);

但是,将上面的代码从模板范式转换为闭包范式的效果与我预期的一样:

function shiftImg() {
  var offset = 0;
  return {
    shift: function() {
      offset++;
      console.log("Offset: " + offset);
    }
  }
}

productImg = shiftImg();
window.setInterval(productImg.shift, 100);


在我的第一个示例中,为什么我无法通过运算符 this 访问 offset


我的答案:
我会在这里发布我的解决方案,因为我无法附加独立的答案。 再次浏览 MDN 的乱七八糟的文档,我了解到了 bind 方法:

function shiftImg() {
  this.offset = 0;
  this.shift =
    function() {
      this.offset++;
      var img = document.getElementById('img');
      img.style.paddingLeft = this.offset + 'px';
      console.log("Offset: " + this.offset);
    };
}

productImg = new shiftImg;
window.setInterval(productImg.shift.bind(productImg), 100);

最佳答案

嵌套函数没有它自己的 this 上下文(它只是引用 window),所以给 this< 分配一个变量 shiftImg 中的方法,您可以在嵌套函数中引用该方法:

function shiftImg() {
  var self = this;
  this.offset = 0;
  this.shift =
    function() {
      self.offset++;
      console.log("Offset: " + self.offset);
    };
}

productImg = new shiftImg();
window.setInterval(productImg.shift, 100);

您需要这样做的原因是因为调用该方法的 setInterval 是在单独的执行上下文中运行的,其中 this 等于 窗口。如果您从 shiftImg() 中调用 this.shift(),您会发现它工作正常,无需添加 self . See this MDN article for more .

或者将匿名函数传递给 setInterval 中的回调方法:

window.setInterval(function() {
    productImg.shift();
}, 100); 

如果您使用对象和 jQuery,那么您会经常遇到这个问题,而 jQuery 的 $.proxy实用程序方法使与上述类似的事情变得相当容易。

关于javascript - 无法通过 'this' 访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22381580/

相关文章:

php - 如何使用包含的 php 文件中的 php 变量

Javascript 函数存储在数组中与存储在变量中

javascript - 通过jquery或javascript获取图片的坐标

javascript - 代码在 JSFiddle 中工作,但在浏览器中不起作用

javascript - jQuery JavaScript 在 View /窗口中检测对象

ruby-on-rails - 从相关对象中获取前 x 个项目

javascript - 用于在 div 中滚动图像的 Jquery 脚本不起作用

javascript - 破解 JS : Thoughts on mixing in some object as arguments (or inner variables) for external functions (like **kwargs) w/o using this

javascript - 使用在 jQuery.on( 调用中对 'this' 进行操作的函数

javascript - (this).attr() 在 jquery.noConflict() 之后停止工作