2014-12-10 4 views
0

매우 간단합니다.이 예제에서 내 범위 작업을 수행하는 방법은 무엇입니까? 스코프의 첫 번째 참조는 갑판 기능에 기록되지만 두 번째 기록은 전역 창에 기록됩니다. 내가 원하는대로 갑판에 두 번째 참조하게하는 방법.내 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! 

    }); 
} 
+1

여기에 여러 번 묻고 답했습니다. 제안 된 사본을보십시오. 나는이 작품이 어떻게 작동하고 그것이 무엇을 의미하는지 정확히 읽으시기 바랍니다. –

답변

3

어느 쪽이 바깥 기능에 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); 
+0

젠장! 나는 너무 가까웠다. 당신의 도움을 주셔서 감사합니다. – heyjohnmurray

+1

또는 forEach에 두 번째 인수를 사용하십시오 : this.suits.forEach (function() ... this)'. –

+0

@ 토라자 부로 : 아! 나는 그것에 대해 몰랐다. 나는 그것을 편집 할 것입니다. – icktoofay

1

U 그렇게 그것을 확인 (?) :

$this = this; 
this.suits.forEach(function(currentSuit){ 

    var scope = $this; 

    console.log(scope); 

}); 
1

저장 먼저 갑판 범위에 대한 참조 변수 ...

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! 

    }); 
} 
1

하나 이 문제를 해결하는 방법은 forEach의 두 번째 인수로 "this"를 전달하는 것입니다. 그래서 당신은

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

다음 새 데크를 호출하기

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

을 편집하는 경우() 두 경우 모두에서 "덱"로그 콘솔 것입니다.

관련 문제