2013-01-08 74 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

「test」是如何被調用的?如何調用'read'?這將決定每個「this」的價值。你爲什麼使用'this'?你是否將'test'作爲構造函數調用?如果是這樣,爲什麼不使用大寫(即'function Test()')開始構造函數名稱的約定呢? – Quentin

+0

如果你想做'new test()。read()' – 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

這完全取決於函數從何處被調用。 我建議閱讀一些有關this關鍵字如果您創建的test

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' 

的實例並調用該實例的方法read也許看看這個SO question

this將指welltest

但是,如果您的代碼不起作用,該方法可能會與另一個上下文一起調用。 也許你添加了一個Eventlistener。並且它的回調函數試圖調用this.write
然後this不會再引用test/your函數的實例。

,你也可以做的是保持什麼上下文中的局部變量一樣

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 

所以當你在write得到儘管read被調用爲它的上下文全局對象Window執行第二種情況看。

繼承人a JSBin