【发布时间】:2014-04-18 08:41:06
【问题描述】:
在下面的 sn-p 中,我尝试从成员函数 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);
【问题讨论】:
-
只有在传递给 setInterval 时才会丢失范围:jsfiddle.net/F8cJc,这是因为当您将函数引用传递给 setInterval 时,它会以
window作为上下文执行,除非你用.bind
标签: javascript scope this private