<分区>
在下面的代码片段中,我尝试从成员函数 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);