what's wrong with my javascript scope

This question already has an answer here:

  • Javascript “this” pointer within nested function 7 answers

  • Either store a reference to this in the enclosing function and use that:

    var me = this;
    this.suits.forEach(function(currentSuit) {
        console.log(me.suits);
    });
    

    Or use bind :

    this.suits.forEach(function(currentSuit) {
        console.log(this.suits);
    }.bind(this));
    

    Or use the second argument to forEach : (This is probably the best solution.)

    this.suits.forEach(function(currentSuit) {
        console.log(this.suits);
    }, this);
    

    你检查它是这样的(?):

     $this = this;
     this.suits.forEach(function(currentSuit){
    
        var scope = $this;
    
        console.log(scope);
    
    });
    

    首先将参考变量保存到甲板作用域中...

    function Deck(){
        var self = this; // save a reference to the deck context
    
        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 = self;
    
            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!
    
        });
    }
    
    链接地址: http://www.djcxy.com/p/94898.html

    上一篇: 我如何在函数中调用变量?

    下一篇: 我的javascript范围有什么问题