我的javascript范围有什么问题

这个问题在这里已经有了答案:

  • 嵌套函数中的Javascript“this”指针7个答案

  • 在封闭函数中存储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);
    

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

     $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/94897.html

    上一篇: what's wrong with my javascript scope

    下一篇: cannot access 'this' in nested function