2013-01-08 2 views
0

이렇게하는 방법이 있습니까?동일한 기능 내의 다른 기능에 액세스하십시오.

function test() 
    { 

     this.write = function(text) 
     { 
      alert(text); 
     } 

     this.read = function() 
     { 
      this.write('foo'); 
      // WRONG WAY 
      // test.write('foo'); 
     } 
    } 

"this.read"에서 "this.write"함수를 어떻게 호출 할 수 있습니까?

편집 :

는 EricG으로 awnser 발견. 위의 코드로 시도해 본 결과 작동합니다. 하지만 내 진짜 코드는 여전히 작동하지 않습니다. 나는 무슨 일이 일어나는지 알아 내야 해.

내부 "THIS.READ"에서 "THIS.WRITE"를 호출하는 방법 단지 'this.write() ". 그냥 그렇게.

감사합니다!

+5

처음에는 '테스트'가 어떻게 호출 되나요? 어떻게'read'가 호출됩니까? 그것은'이'의 가치가 각각 무엇인지 결정할 것입니다. 왜 이걸 사용하는거야? 'test '를 생성자 함수로 부르시겠습니까? 그렇다면 왜 생성자 함수 이름을 대문자로 시작하는 관례를 사용하지 않는가? (즉,'function Test()')? – Quentin

+0

'new test(). read()'를하고 싶다면'this.write()'를 사용하십시오. – EricG

+0

거룩한 어머니 ...나는 이렇게 많은 시간을 시도하고 "this.foo()"다른 함수를 실행했다. 그것은 그 예제와 함께 작동하지만 내 코드 (다른 코드는 여기에 넣지 않아도 됨)가 작동하지 않습니다. 어쨌든. 도움 EicG 및 Quentin에 감사드립니다. – Alexandre

답변

1
function test() 
{ 
    this.write = function(text) 
    { 
     alert(text); 
    } 

    this.read = function() 
    { 
     this.write('foo'); 
    } 
} 

var a = new test(); 
a.read(); 

jsFiddle를 호출하는 것입니다

0

이 시도 :

function test() 
{ 

    this.write = function(text) 
    { 
     alert(text); 
    } 

    this.read = function() 
    { 
     this.write('foo'); 
    } 
} 

var t = new test(); 
t.read(); 

fiddle

0
function test() 
{ 
    var self = this; 

    this.write = function(text) 
    { 
     alert(text); 
    }; 

    this.read = function() 
    { 
     self.write('foo'); 
    }; 

    // depending on browser versions or included libraries. 
    this.another = function() { 
     this.write('foo'); 
    }.bind(this); 
} 

또한 바인드 호출없이 사용할 수도 있지만 특정 상황에서는 'this'의 의미가 변경 될 수 있습니다.

0

전적으로 함수가 호출되는 위치에 따라 달라집니다. 난 당신이 인스턴스의 방법 readtest

function test() 
{ 

    this.write = function(text) 
    { 
     alert(text); 
    } 

    this.read = function() 
    { 
     this.write('foo'); 
    } 
} 
var inst = new test() 
inst.read() //foo 
inst.read.call() //Uncaught TypeError: Object [object Window] has no method 'write' 

의 인스턴스를 만들고 호출하면 어쩌면이 SO question

한 번 봐 걸릴 this 키워드에 대한 좀 더 읽어 제안, this는 참조합니다 ,이 인스턴스 test

그러나 코드가 작동하지 않으면이 메서드는 다른 컨텍스트로 호출되었을 수 있습니다. 아마 당신이 추가 한 EventListener. 그리고 그것의 콜백 함수는 this.write
을 호출하고, this은 더 이상 test/your 함수의 인스턴스를 참조하지 않을 것입니다. 당신이 read이 문맥으로 전역 개체 Window로 호출 있지만 write가 실행됩니다 두 번째 경우에서 보는 것처럼 당신은 또한 그래서

function test() 
{ 
    var context = this; 
    this.write = function(text) 
    { 
     alert(text); 
    } 

    this.read = function() 
    { 
     context.write('foo'); 
    } 
} 
var inst = new test() 
inst.read() // foo 
inst.read.call() //foo 

같은 지역 변수 컨텍스트를 유지한다 무엇을 할 수 있는지

.

Heres a JSBin

관련 문제