javascript - 我的 javascript 作用域出了什么问题

标签 javascript

很简单,我如何让我的范围在这个例子中工作。范围的第一个引用记录到甲板函数,但第二个引用记录到全局窗口。我如何让第二个引用套牌像我想要的那样。

谢谢!

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/

相关文章:

javascript - 为什么 Bower 建议忽略缩小的源文件?

javascript - $ ('div[class^="ii gt"]') 适用于 chrome 而不是 firefox?

javascript - 将文件名传递给我的 javascript 文件

javascript - Stream.end() 是同步的吗?

javascript - JSON:parseInt 不起作用

javascript - foreach 完成渲染时的自定义绑定(bind)

javascript - 将 wiredep 返回的所有文件连接到一个文件中

javascript - 带 HTML 选择的 Jquery 类别更新系统

javascript - WebSocketGateway 中的 WsException 不起作用

javascript - 在我的购物 list 应用程序中,每件商品有多个按钮,而不是每件商品只有一个按钮?