2012-02-11 2 views
0

클래스 로봇이 있다고 가정 해 보겠습니다.클래스 내부의 변수를 참조 할 때 ... "this." 우리가 함수에 있기 때문에 작동하지 않습니다

변수는 hand lefthand, hand righthand, leg leftlegleg rightleg입니다. leghand 클래스는 int lengthint width을 포함합니다.

this.lefthand.length = 100; 
this.leftleg.length = 200; 

function switch_length() { 
this.lefthand.length = 300; //This is wrong. So what can I do instead to refer to lefthand?? 
this.leftleg.length = 400; //This is wrong. So what can I do instead to refer to leftleg?? 
} 

this.button.addEventlistener (... switch_length()) 
+0

를 사용하여 [바인딩] (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind). –

+0

티타늄에 적용 할 수 있습니까? 이 링크는 mozilla 웹 javascirpt 용입니다. –

+0

링크의 호환성 섹션을 참조하십시오. 티타늄 문서가 있으면 찾아보십시오. 아니면 그냥 사용해보십시오. 또한보십시오 : http://developer.appcelerator.com/questions/newest –

답변

0

자바에서는 호출중인 함수의 컨텍스트를 정의 할 수 있습니다. 나는 예제와 함께이 문제를 설명하는 더 나은, 그래서 여기 간다 :이 질문에 응답 한 경우

var something = { 
    'foobar': 'var 1 value', 
    'foo': function() { 
     alert(this.var1); 
    } 
} 

var something_else = { 
    'foobar': 'some completely other value' 
} 

function bar() { 
    alert(this.foobar); 
} 

something.foo(); //alerts 'var 1 value' 
bar(); //produces an error 
bar.call(something); //alerts 'var 1 value' 
bar.call(something_else); //alerts 'some completely other value' 

function.call(context, [arg1, [arg2, [...]]]);

, 내 대답을 받아 들일 수 있는지 확인하십시오.

편집 : 는 여기에 또 다른 예를의

function create() { 
    return { 
     'hand': { 
      'length': 100 
     }, 
     'leg': { 
      'length': 100 
     } 
    } 
} 

function set_length(hand, leg) { 
    this.hand.length = hand; 
    this.leg.length = leg; 
} 

var left = create(), 
    right = create(); 

set_length.call(left, 200, 300); 
set_length.call(right, 50, 150); 
+0

이것 좀 봐 : http://stackoverflow.com/questions/9247887/titanium-javascript-that-does-not-work –