很简单,我如何让我的范围在这个例子中工作。范围的第一个引用记录到甲板函数,但第二个引用记录到全局窗口。我如何让第二个引用套牌像我想要的那样。
谢谢!
http://jsbin.com/neqevo/1/edit?js
function Deck(){
this.suits = [ // this is an array now
{
'suit': 'diamonds',
'symbol': '♦',
'color': 'red'
}
]; // close suits
this.cardValues = [
{
'name': 'ace',
'face': 'A',
'value': 1
}
]; // close cardValues
this.cards = [];
console.log(this);
this.suits.forEach(function(currentSuit){
var scope = this;
console.log(scope);
// scope doesn't work.
// obviously, scope references window
// so how do i get it to refer to the deck like it's supposed to.
// i looked into using call and apply, and even though the concepts
// made sense i couldn't figure it out.
// fuck this is frustrating!
});
}
最佳答案
在封闭函数中存储对 this
的引用并使用它:
var me = this;
this.suits.forEach(function(currentSuit) {
console.log(me.suits);
});
或者使用绑定(bind)
:
this.suits.forEach(function(currentSuit) {
console.log(this.suits);
}.bind(this));
或者使用forEach
的第二个参数:(这可能是最好的解决方案。)
this.suits.forEach(function(currentSuit) {
console.log(this.suits);
}, this);
关于javascript - 我的 javascript 作用域出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27393278/